path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
docs/src/app/components/pages/components/SvgIcon/ExampleSimple.js
kasra-co/material-ui
import React from 'react'; import {blue500, red500, greenA200} from 'material-ui/styles/colors'; import SvgIcon from 'material-ui/SvgIcon'; const iconStyles = { marginRight: 24, }; const HomeIcon = (props) => ( <SvgIcon {...props}> <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" /> </SvgIcon> ); const SvgIconExampleSimple = () => ( <div> <HomeIcon style={iconStyles} /> <HomeIcon style={iconStyles} color={blue500} /> <HomeIcon style={iconStyles} color={red500} hoverColor={greenA200} /> </div> ); export default SvgIconExampleSimple;
node_modules/react-router/es/IndexRoute.js
firdiansyah/crud-req
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
demo/badge/badge.js
eferte/react-mdl-1
import React from 'react'; import Icon from '../../src/Icon'; import Badge from '../../src/Badge'; class Demo extends React.Component { render() { return ( <div> <p>Number badge on icon</p> <Badge text="1"> <Icon name="account_box" /> </Badge> <p>Icon badge on icon</p> <Badge text="♥"> <Icon name="account_box" /> </Badge> <p>Number badge</p> <Badge text="4">Inbox</Badge> <p>Icon badge</p> <Badge text="♥">Mood</Badge> </div> ); } } React.render(<Demo />, document.getElementById('app'));
src/routes/Home/index.js
Raphael67/react-restify-mysql
import React from 'react' import DefaultLayout from '../../layouts/Default' export default class Home extends React.Component { render() { return ( <DefaultLayout currentPage='home'> <div>This is the home page!</div> </DefaultLayout> ) } }
src/components/run.js
nfrigus/react-webpack
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/action/pageview.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPageview = (props) => ( <SvgIcon {...props}> <path d="M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-3.21 14.21l-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z"/> </SvgIcon> ); ActionPageview = pure(ActionPageview); ActionPageview.displayName = 'ActionPageview'; export default ActionPageview;
client/components/media_by_day.js
jaischeema/panorma
import React from 'react'; import MediaByInterval from './media_by_interval'; import moment from 'moment'; export default class MediaByDay extends MediaByInterval { fetchParams(props) { return { year: props.params.year, month: props.params.month, day: props.params.day } } titleElements() { let titleDate = moment({ month: this.props.params.month - 1, year: this.props.params.year, day: this.props.params.day }) return <span>{titleDate.format('Do MMMM YYYY')}</span> } }
index.ios.js
gfogle/multi-platform-react
'use strict'; // it is important to import the react package before anything else import React from 'react'; import { AppRegistry } from 'react-native'; import Root from './src/components/root/root'; AppRegistry.registerComponent('MultiPlatformReact', () => Root);
src/common/components/Routes.js
aretheyrobots/prove-it
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import LoginPage from '../../pages/login/page'; import ViewPage from '../../pages/view/page'; import SpikePage from '../../pages/spike/page'; export default ( <Route path="/" component={App}> <IndexRoute component={LoginPage} /> <Route path="spike/:id" component={SpikePage} /> <Route path="view/:id" component={ViewPage} /> </Route> );
src/index.js
jonjomckay/stividor
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/Problem.js
CISC475-Group2/parsons-ui
import React, { Component } from 'react'; import { DragSource, DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import Block from './Block'; import BlockList from './BlockList'; import AvailableBlocksSpace from './AvailableBlocksSpace' class Problem extends Component { render() { return ( <div className="problem col-lg-12"> <div className="page-header"> <h1>Problem 4</h1> </div> <pre className="code-space">{this.props.baseBlockString}</pre> <pre> <Block block={this.props.baseBlock} onMoveBlock={this.props.onMoveBlock} onSwapBlocks={this.props.onSwapBlocks} /> <AvailableBlocksSpace onMoveBlock={this.props.onMoveBlock}> <BlockList blocks={this.props.blocks} onMoveBlock={this.props.onMoveBlock} onSwapBlocks={this.props.onSwapBlocks} /> </AvailableBlocksSpace> </pre> <div className="btn-group" role="group" aria-label="..."> <button type="button" className="btn btn-default" onClick={this.props.onReset.bind(this)}>Reset</button> <button type="button" className="btn btn-default" >Submit</button> </div> </div> ); } }; export default DragDropContext(HTML5Backend)(Problem);
src/statics/UserNotFound.js
Sekhmet/busy
import React from 'react'; import { FormattedMessage } from 'react-intl'; const UserNotFound = () => <div className="text-center my-5"> <h3> <FormattedMessage id="user_not_found" defaultMessage="User not found" /> </h3> </div>; export default UserNotFound;
src/templates/blogPost.js
asunny72/IdeaNation
import React from 'react' import Helmet from 'react-helmet' import { DiscussionEmbed } from "disqus-react" import { graphql } from "gatsby" import Layout from '../components/layout' import HeaderGeneric from '../components/HeaderGeneric' class BlogPost extends React.Component { constructor(data) { super(); this.data = data; } render() { const data = this.data.data; if (!data || !(data.markdownRemark || data.contentfulBlogPost)) { return; } const post = data.markdownRemark? extractPostFromLocalBlogs(data) : extractPostFromContenfulBlogs(data); const disqusShortname = "ideanation"; const disqusConfig = { identifier: post.id, title: post.title, }; return ( <Layout> <Helmet title="BlogPost" /> <HeaderGeneric /> <div id="main" className="main"> <section id="content" className="main"> <h1>{post.title}</h1> <div white-space="pre-wrap" dangerouslySetInnerHTML={{ __html: post.html }} /> </section> <section id="content" className="main"> <DiscussionEmbed shortname={disqusShortname} config={disqusConfig} /> </section> </div> </Layout> ) } } const extractPostFromLocalBlogs = data => { const entry = data.markdownRemark; return { id: entry.id, title: entry.frontmatter.title, html: entry.html }; }; const extractPostFromContenfulBlogs = data => { const entry = data.contentfulBlogPost; return { id: entry.id, title: entry.title, html: entry.childContentfulBlogPostBodyTextNode.childMarkdownRemark.html }; }; export default BlogPost export const query = graphql` query($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title } } contentfulBlogPost(slug: { eq: $slug }) { id title childContentfulBlogPostBodyTextNode { childMarkdownRemark { html } } } } `
src/scripts/app.js
lixmal/keepass4web
import jQuery from 'jquery' import Css from '../style/app.css' import React from 'react' import ReactDOM from 'react-dom' import Router from 'react-router/lib/Router' import Route from 'react-router/lib/Route' import useRouterHistory from 'react-router/lib/useRouterHistory' import withRouter from 'react-router/lib/withRouter' import { createHashHistory } from 'history' import Viewport from './Viewport' import UserLogin from './UserLogin' import BackendLogin from './BackendLogin' import DBLogin from './DBLogin' const View = withRouter(Viewport) const UserForm = withRouter(UserLogin) const BackendForm = withRouter(BackendLogin) const DBForm = withRouter(DBLogin) const appHistory = useRouterHistory(createHashHistory)() // global namespace window.KeePass4Web = {} KeePass4Web.checkAuth = function (nextState, replace, callback) { return KeePass4Web.ajax('authenticated', { error: function (r, s, e) { var auth if (r.status == 401 && r.responseJSON) auth = r.responseJSON.message else KeePass4Web.error(r, s, e) if (!auth) return var state = nextState && nextState.location.state // route to proper login page if unauthenticated // in that order if (!auth.user) { KeePass4Web.clearStorage() replace({ state: state, pathname: '/user_login' }) } else if (!auth.backend) { var template = KeePass4Web.getSettings().template if (template.type === 'redirect') { window.location = template.url // stopping javascript execution to prevent redirect loop throw 'Redirecting' } else if (template.type === 'mask') replace({ state: state, pathname: '/backend_login' }) } else if (!auth.db) { replace({ state: state, pathname: '/db_login' }) } }.bind(this), complete: callback, }) } // simple wrapper for ajax calls, in case implementation changes KeePass4Web.ajax = function (url, conf) { conf.url = url // set defaults conf.method = typeof conf.method === 'undefined' ? 'POST' : conf.method conf.dataType = typeof conf.dataType === 'undefined' ? 'json' : conf.dataType if (typeof conf.headers === 'undefined') { conf.headers = {} } conf.headers['X-CSRF-Token'] = KeePass4Web.getCSRFToken() KeePass4Web.restartTimer(true) return jQuery.ajax(conf) } // leave room for implementation changes KeePass4Web.clearStorage = function () { localStorage.removeItem('settings') localStorage.removeItem('CSRFToken') } KeePass4Web.setCSRFToken = function (CSRFToken) { localStorage.setItem('CSRFToken', CSRFToken || '') } KeePass4Web.getCSRFToken = function () { return localStorage.getItem('CSRFToken') || null } KeePass4Web.setSettings = function (settings) { var stored = KeePass4Web.getSettings() for (var k in settings) { stored[k] = settings[k] } localStorage.setItem('settings', JSON.stringify(stored)) } KeePass4Web.getSettings = function () { var settings = localStorage.getItem('settings') if (settings) return JSON.parse(settings) return {} } KeePass4Web.timer = false KeePass4Web.restartTimer = function (val) { if (typeof val !== 'undefined' ) KeePass4Web.timer = val return KeePass4Web.timer } KeePass4Web.error = function (r, s, e) { // ignore aborted requests if (e === 'abort') return if (r.status == 401) { if (this.props && this.props.router) { // redirect first, to hide sensitive data this.props.router.replace('/db_login') this.props.router.replace({ state: { info: 'Session expired' }, pathname: '/' }) } else { alert('Your session expired') location.reload() } } else { let error = e if (r.responseJSON) error = r.responseJSON.message // disable remaining loading masks if (this.state) { this.setState({ groupMask: false, nodeMask: false, }) } alert(error) } } ReactDOM.render( <Router history={appHistory}> <Route path="/" component={View} onEnter={KeePass4Web.checkAuth} /> <Route path="/user_login" component={UserForm} /> <Route path="/backend_login" component={BackendForm} /> <Route path="/db_login" component={DBForm} /> </Router>, document.getElementById('app-content') )
docs/pages/api-docs/table-pagination.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/table-pagination'; const requireRaw = require.context('!raw-loader!./', false, /\/table-pagination\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
docs/src/pages/faq.js
Gisto/Gisto
import React from 'react'; import {Helmet} from "react-helmet"; import Header from 'components/header'; import Footer from 'components/footer'; const Faq = () => ( <React.Fragment> <Helmet> <title>F.A.Q.</title> </Helmet> <Header/> <h1>F.A.Q.</h1> <section className="whiter boxes page-faq inner"> <div className="w-container content-container"> <div className="w-row"> <div className="w-col w-col-3 w-clearfix side-container"> <h2>QUESTIONS</h2> <nav> <ul> <li><a className="innsite" href="#what-is-gisto">What is Gisto?</a> </li> <li><a className="innsite" href="#auth">Authentication</a></li> <li><a className="innsite" href="#do-you-use-server">Do you use backend server? </a> </li> <li><a className="innsite" href="#who-can-see-my-gists">Who can see my gists? </a> </li> <li><a className="innsite" href="#run-as-portable">Use gisto as portable application in windows. </a> </li> <li><a className="innsite" href="#do-you-plan-to-add-feature">Do you plan to support / add support for [future-name-here]? </a> </li> <li><a className="innsite" href="#issues-bugs-features">Issues, bug reporting, pull and feature requests </a> </li> <li><a className="innsite" href="#how-to-contact">How to contact us </a> </li> </ul> </nav> </div> <div className="w-col w-col-9 w-clearfix"> <h2 id="what-is-gisto">What is Gisto?</h2> <p>Gisto is a code snippet manager that runs on GitHub Gists and adds additional features such as searching, tagging and sharing gists while including a rich code editor. </p> <p>Gisto is cross platform and is in constant sync with GitHub so you can view and edit your Gists via both Gisto and GitHub. </p> <h2 id="auth">Authentication</h2> <p>Gisto authenticates to GitHub by using basic authentication over SSL and retrieving an oAuth2 token thus the need for your GitHub user and password. </p> <p>Gisto only saves the oAuth2 token received after authenticating and nothing else. If you would rather to supply your own access token without providing Gisto your login details you may manually create an access token from the account settings at GitHub and login using the generated token. </p> <p>This token will be saved permanently until you log out.</p> <h2 id="do-you-use-server">Do you use backend server?</h2> <p>Gisto is using GitHub gist API and communicates directly with Github, no 3rd party server or database involved in gist management. </p> <p>However we do use a backend server for "notifications and sharing service", the only data stored is username and gist ID and this is to allow Gisto to notify user if there are Gists shared with him. </p> <p>You also have the option of running your own notification server so you can be sure your data is secure. </p> <h2 id="who-can-see-my-gists">Who can see my Gists?</h2> <p>As per GitHub Guidelines Gists are not private and are available to the public. </p> <p>The difference between secret and public Gists is that public Gists are listed on GitHub website for public viewing and searching while secret Gists are not </p> <h2 id="run-as-portable">Use gisto as portable application on windows?</h2> <blockquote> Please note this instructions refers to legacy version (up to v0.3.2) </blockquote> <p>For a non-installer version of Gisto, you can:</p> <ul className="fa-ul"> <li className="icons-li"><i className="fa fa-chevron-circle-right" /> Download a ZIP file of Windows Version from Gisto "Nightly" builds: <a href="http://build.gistoapp.com">build.gistoapp.com </a> and extract it to some directory of your choosing. </li> <li className="icons-li"><i className="fa fa-chevron-circle-right" /> Create a empty file in directory you've extracted Gisto ZIP named <em>gisto.bat</em> </li> <li className="icons-li"><i className="fa fa-chevron-circle-right" /> Edit <em>gisto.bat</em> file and add the following content: <code>gisto.exe --data-path="./gistoData" </code> </li> <li className="icons-li"><i className="fa fa-chevron-circle-right" /> Start Gisto by double-click the <em>gisto.bat</em> file. </li> </ul> <p>You have now your portable version of Gisto and all data will be saved in directory named <em>gistoData</em>, relative to path where you are running Gisto from. </p> <p>In order to update portable Gisto - just download new version ZIP and extract it by overwriting the existing files. </p> <h2 id="do-you-plan-to-add-feature">Do you plan to support / add support for [<i>future-name-here</i>]? </h2> <p>Please open a feature request in our <a href="https://github.com/Gisto/Gisto/issues">issue tracker </a>, we appreciate and strive for suggestions on how to improve Gisto. </p> <h2 id="issues-bugs-features">Issues, bug reporting, pull and feature requests </h2> <p>Please feel free to add a bug / feature request / suggestions to the <a href="https://github.com/Gisto/Gisto/issues">issue tracker </a>. Pull requests are also very welcome as well. </p> <h2 id="how-to-contact">How to contact us</h2> <p>Twitter: <a href="https://twitter.com/gistoapp">@gistoapp</a></p> <p>Email: [email protected]</p> <p>Issue tracker: <a href="https://github.com/Gisto/Gisto/issues">Issue tracker at GitHub </a> </p> </div> </div> </div> </section> <Footer/> </React.Fragment> ); export default Faq;
actor-apps/app-web/src/app/components/modals/InviteUser.react.js
WangCrystal/actor-platform
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ActorClient from 'utils/ActorClient'; import { KeyCodes } from 'constants/ActorAppConstants'; import InviteUserActions from 'actions/InviteUserActions'; import InviteUserByLinkActions from 'actions/InviteUserByLinkActions'; import ContactStore from 'stores/ContactStore'; import InviteUserStore from 'stores/InviteUserStore'; import ContactItem from './invite-user/ContactItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return ({ contacts: ContactStore.getContacts(), group: InviteUserStore.getGroup(), isOpen: InviteUserStore.isModalOpen() }); }; const hasMember = (group, userId) => undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId); @ReactMixin.decorate(IntlMixin) class InviteUser extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = _.assign({ search: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); InviteUserStore.addChangeListener(this.onChange); ContactStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { InviteUserStore.removeChangeListener(this.onChange); ContactStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { InviteUserActions.hide(); }; onContactSelect = (contact) => { const { group } = this.state; InviteUserActions.inviteUser(group.id, contact.uid); }; onInviteUrlByClick = () => { InviteUserByLinkActions.show(this.state.group); InviteUserActions.hide(); }; onKeyDown = (event) => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onSearchChange = (event) => { this.setState({search: event.target.value}); }; render() { const { contacts, group, search, isOpen } = this.state; let contactList = []; if (isOpen) { _.forEach(contacts, (contact, i) => { const name = contact.name.toLowerCase(); if (name.includes(search.toLowerCase())) { if (!hasMember(group, contact.uid)) { contactList.push( <ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/> ); } else { contactList.push( <ContactItem contact={contact} key={i} isMember/> ); } } }, this); } if (contactList.length === 0) { contactList.push( <li className="contacts__list__item contacts__list__item--empty text-center"> <FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/> </li> ); } return ( <Modal className="modal-new modal-new--invite contacts" closeTimeoutMS={150} isOpen={isOpen} style={{width: 400}}> <header className="modal-new__header"> <a className="modal-new__header__icon material-icons">person_add</a> <h4 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/> </h4> <div className="pull-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onClose} secondary={true} style={{marginTop: -6}}/> </div> </header> <div className="modal-new__body"> <div className="modal-new__search"> <i className="material-icons">search</i> <input className="input input--search" onChange={this.onSearchChange} placeholder={this.getIntlMessage('inviteModalSearch')} type="search" value={this.state.search}/> </div> <a className="link link--blue" onClick={this.onInviteUrlByClick}> <i className="material-icons">link</i> {this.getIntlMessage('inviteByLink')} </a> </div> <div className="contacts__body"> <ul className="contacts__list"> {contactList} </ul> </div> </Modal> ); } } export default InviteUser;
src/components/Bookmark.js
Jalissa/rss-feed-client
import React from 'react'; const Bookmark = (props) => { let style = { color: '#ccc'}; if(props.markBookmarkFlag){ style.color = '#000'; } const onClick = (evt) => { evt.stopPropagation(); const element = evt.target; props.boundActions.toggleBookmark(element, props.feed); }; return ( <span onClick={onClick} style={style} className="glyphicon glyphicon-bookmark" aria-hidden="true"/> ); }; export default Bookmark;
src/server.js
BlackAngus/BVPHackathon
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import bodyParser from 'body-parser'; import twilio from 'twilio'; import Firebase from 'firebase'; // Twilio Setup. const accountSid = 'ACa54c5209e1735c0762bdb2d3da27d7ce'; const authToken = '82fc0731876d1c9022d3963bca07f2ff'; const client = twilio(accountSid, authToken); // Firebase Setup. const myRootRef = new Firebase('https://bvphackathon.firebaseio.com/'); const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); server.use(bodyParser.json()); server.post('/getHelp', async (req, res, next) => { var Workers = myRootRef.child('Workers'); Workers.once('value', function(data){ console.log("Data from Firebase: ", data.val()); var memberArray = []; // Push the mmebers into an array. for(var worker in data.val()) memberArray.push(data.val()[worker]); // This will be random for now but a proper algorithm will help. // Random number generator 0 - 1. var randomWorker = memberArray[Math.floor((Math.random() * memberArray.length))]; console.log("Contacting: ", randomWorker); client.messages.create({ body: [ randomWorker.name, "Your help is need in 5 mintues at", "Job Site: DNA Pizza", "Address: 375 11th St, San Francisco, CA 94103", "Phone: (415) 626-0166", "Description: The job is 2hrs long and you will make $40 for your services." ].join("\n"), to: randomWorker.phone, from: "+19782212765" }, function(err, message) { console.log(req.body); if(err) return res.status(200).send("<response>false</response>"); console.log(message.sid); return res.status(200).send("<response>true</response>"); }); }); }); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://0.0.0.0:' + server.get('port')); if (process.send) { process.send('online'); } });
app/javascript/flavours/glitch/features/ui/components/column_loading.js
Kirishima21/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Column from 'flavours/glitch/components/column'; import ColumnHeader from 'flavours/glitch/components/column_header'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class ColumnLoading extends ImmutablePureComponent { static propTypes = { title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), icon: PropTypes.string, }; static defaultProps = { title: '', icon: '', }; render() { let { title, icon } = this.props; return ( <Column> <ColumnHeader icon={icon} title={title} multiColumn={false} focusable={false} placeholder /> <div className='scrollable' /> </Column> ); } }
client/src/components/search/searchPage/NoResults.js
BhaveshSGupta/FreeCodeCamp
import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { query: PropTypes.string }; function NoResults({ query }) { return ( <div className='no-results-wrapper'> <p> We could not find anything relating to <em>{query}</em> </p> </div> ); } NoResults.displayName = 'NoResults'; NoResults.propTypes = propTypes; export default NoResults;
examples/react-redux/src/store/routes.js
rangle/redux-segment
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import App from '../containers/App'; import AboutPage from '../containers/AboutPage'; import CounterPage from '../containers/CounterPage'; export default ( <Route path="/" component={ App }> <IndexRoute component={ CounterPage }/> <Route path="about" component={ AboutPage }/> </Route> );
packages/lightning-components/Select/index.js
DaReaper/lightning-app
import React from 'react' import reactCSS, { hover } from 'reactcss' import _ from 'lodash' import { colors, css, fonts } from '../helpers' export const Media = (props) => { const styles = reactCSS({ 'default': { select: { background: 'transparent', border: 'none', height: 30, boxShadow: 'inset 0 0 0 1px #ccc', borderRadius: 2, textTransform: 'uppercase', color: '#aaa', cursor: 'pointer', outline: 'none', fontSize: fonts.sizes.medium, transition: 'box-shadow 200ms ease-out, color 200ms ease-out', }, }, 'hover': { select: { boxShadow: 'inset 0 0 0 1px #888', color: '#777', }, }, 'bare': { select: { boxShadow: 'none', padding: 0, }, }, ...css.build('media', 'color', colors), }, props) return ( <select style={ styles.select } value={ props.value } onChange={ props.onChange }> { _.map(props.options, (option) => { return <option key={ option.value } value={ option.value }>{ option.label }</option> }) } </select> ) } export default hover(Media)
app/actions/entryActions.js
JasonEtco/flintcms
import React from 'react' import { push } from 'react-router-redux' import graphFetcher from 'utils/graphFetcher' import formatFields from 'utils/formatFields' import { getSlugFromId } from 'utils/helpers' import { newToast, errorToasts } from './uiActions' export const REQUEST_ENTRIES = 'REQUEST_ENTRIES' export const RECEIVE_ENTRIES = 'RECEIVE_ENTRIES' export const NEW_ENTRY = 'NEW_ENTRY' export const UPDATE_ENTRY = 'UPDATE_ENTRY' export const DELETE_ENTRY = 'DELETE_ENTRY' export const ENTRY_DETAILS = 'ENTRY_DETAILS' /** * Creates a new Entry * @param {string} title * @param {string} section * @param {string} status * @param {string} dateCreated * @param {object} rawOptions */ export function newEntry (title, section, status, dateCreated, rawOptions) { return async (dispatch, getState) => { const { fields, sections, user } = getState() const options = await formatFields(rawOptions, fields.fields) const query = `mutation ($data: EntriesInput!) { addEntry(data: $data) { _id title slug status fields { fieldId handle value } section author { username } dateCreated } }` const variables = { data: { title, section, status, dateCreated, fields: options, author: user._id } } return graphFetcher(query, variables) .then((json) => { const { addEntry } = json.data.data dispatch({ type: NEW_ENTRY, addEntry }) dispatch(newToast({ message: <span><b>{addEntry.title}</b> has been created!</span>, style: 'success' })) const sectionSlug = getSlugFromId(sections.sections, addEntry.section) dispatch(push(`/entries/${sectionSlug}/${addEntry._id}`)) }) .catch(errorToasts) } } /** * Saves updates of an existing Entry * @param {string} _id * @param {object} data */ export function updateEntry (_id, data) { return async (dispatch, getState) => { const state = getState() const { title, status, dateCreated, ...fields } = data const options = await formatFields(fields, state.fields.fields) const query = `mutation ($_id: ID!, $data: EntriesInput!) { updateEntry(_id: $_id, data: $data) { _id title status fields { fieldId handle value } } }` const variables = { _id, data: { title, status, dateCreated, fields: options } } return graphFetcher(query, variables) .then((json) => { const updatedEntry = json.data.data.updateEntry dispatch({ type: UPDATE_ENTRY, updateEntry: updatedEntry }) dispatch(newToast({ message: <span><b>{updatedEntry.title}</b> has been updated!</span>, style: 'success' })) }) .catch(errorToasts) } } /** * Posts to GraphQL to delete an Entry * @param {string} _id * @param {boolean} [redirect=false] - Redirect to the entries page after deleting the entry */ export function deleteEntry (_id, redirect = false) { return (dispatch) => { const query = `mutation ($_id:ID!) { removeEntry(_id: $_id) { _id title } }` return graphFetcher(query, { _id }) .then((json) => { const { removeEntry } = json.data.data if (redirect) dispatch(push('/entries')) dispatch({ type: DELETE_ENTRY, id: removeEntry._id }) dispatch(newToast({ message: <span><b>{removeEntry.title}</b> has been deleted.</span>, style: 'success' })) }) .catch(errorToasts) } } /** * Gets the details (fields object) of an Entry * @param {string} _id - Mongo ID of Entry. */ export function entryDetails (_id) { return (dispatch) => { const query = `query ($_id:ID!) { entry (_id: $_id) { fields { fieldId handle value } } }` return graphFetcher(query, { _id }) .then((json) => { const { entry } = json.data.data dispatch({ type: UPDATE_ENTRY, updateEntry: { _id, ...entry } }) }) .catch(errorToasts) } }
stories/components/quoteBanner/index.js
tskuse/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import QuoteBanner from 'shared/components/quoteBanner/quoteBanner'; storiesOf('shared/components/quoteBanner', module) .add('Default', () => ( <QuoteBanner author="James bond" quote="I always enjoyed learning a new tongue" /> ));
web/themes/custom/proyectofinal/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
kevinmora94/proyectoDrupal
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
app/app.js
lishengzxc/random
import './app.scss'; import styles from './views/Page/Page.scss'; import React from 'react'; import SideBar from './views/SideBar/SideBar'; import Header from './views/Header/Header'; import TeamList from './views/TeamList/TeamList'; import AddTeamButton from './views/AddTeamButton/AddTeamButton'; import EditTeamButton from './views/EditTeamButton/EditTeamButton'; import AddTeamList from './views/AddTeamList/AddTeamList'; import Setup from './views/Setup/Setup'; import MessageBox from './views/MessageBox/MessageBox'; import RandomPage from './views/RandomPage/RandomPage'; import cx from 'classnames'; import Router from 'react-router'; import RandomStore from './stores/random-store'; var Route = Router.Route; var RouteHandler = Router.RouteHandler; var getPageState = () => ({ pageState: RandomStore.getPageState() }); var App = React.createClass({ getInitialState: function () { return getPageState(); }, onSlide: function () { this.setState(getPageState()); }, componentDidMount: function () { RandomStore.addChangeListener(this.onSlide); }, componentWillUnmount: function () { RandomStore.removeChangeListener(this.onSlide); }, render: function () { var classList = this.state.pageState ? [styles.page, styles.slide] : [styles.page]; return ( <div className={styles.div}> <SideBar /> <Header /> <div className={cx(classList)}> <div className={cx(styles.wrapper)}> <RouteHandler /> </div> </div> <AddTeamButton visibility={ window.location.hash.substr(1) === '/addTeam' || window.location.hash.substr(1) === '/setup' || window.location.hash.substr(1) === '/randomPage' || window.location.hash.substr(1) === '/editTeam'} /> <EditTeamButton visibility={ window.location.hash.substr(1) === '/randomPage'} /> </div> ) } }); var routes = ( <Route handler={App}> <Route path="/" handler={TeamList} /> <Route path="addTeam" handler={AddTeamList} /> <Route path="setup" handler={Setup} /> <Route path="randomPage" handler={RandomPage} /> <Route path="editTeam" handler={AddTeamList} /> </Route> ); Router.run(routes, Router.HashLocation, (Root) => { React.render(<Root />, document.body); });
app/javascript/mastodon/features/ui/util/react_router_helpers.js
SerCom-KC/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import ColumnLoading from '../components/column_loading'; import BundleColumnError from '../components/bundle_column_error'; import BundleContainer from '../containers/bundle_container'; // Small wrapper to pass multiColumn to the route components export class WrappedSwitch extends React.PureComponent { render () { const { multiColumn, children } = this.props; return ( <Switch> {React.Children.map(children, child => React.cloneElement(child, { multiColumn }))} </Switch> ); } } WrappedSwitch.propTypes = { multiColumn: PropTypes.bool, children: PropTypes.node, }; // Small Wrapper to extract the params from the route and pass // them to the rendered component, together with the content to // be rendered inside (the children) export class WrappedRoute extends React.Component { static propTypes = { component: PropTypes.func.isRequired, content: PropTypes.node, multiColumn: PropTypes.bool, componentParams: PropTypes.object, }; static defaultProps = { componentParams: {}, }; renderComponent = ({ match }) => { const { component, content, multiColumn, componentParams } = this.props; return ( <BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}> {Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>} </BundleContainer> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { component: Component, content, ...rest } = this.props; return <Route {...rest} render={this.renderComponent} />; } }
blueocean-material-icons/src/js/components/svg-icons/action/settings-power.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettingsPower = (props) => ( <SvgIcon {...props}> <path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm2-22h-2v10h2V2zm3.56 2.44l-1.45 1.45C16.84 6.94 18 8.83 18 11c0 3.31-2.69 6-6 6s-6-2.69-6-6c0-2.17 1.16-4.06 2.88-5.12L7.44 4.44C5.36 5.88 4 8.28 4 11c0 4.42 3.58 8 8 8s8-3.58 8-8c0-2.72-1.36-5.12-3.44-6.56zM15 24h2v-2h-2v2z"/> </SvgIcon> ); ActionSettingsPower.displayName = 'ActionSettingsPower'; ActionSettingsPower.muiName = 'SvgIcon'; export default ActionSettingsPower;
src/App.js
shihlinlu/tesla-range-calculator
import React, { Component } from 'react'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import TeslaCarContainer from './containers/TeslaCarContainer'; import TeslaStatsContainer from './containers/TeslaStatsContainer'; import TeslaSpeedCounterContainer from './containers/TeslaSpeedCounterContainer'; import TeslaTempCounterContainer from './containers/TeslaTempCounterContainer'; import TeslaClimateContainer from './containers/TeslaClimateContainer'; import TeslaWheelsContainer from './containers/TeslaWheelsContainer'; import TeslaNotice from './components/TeslaNotice/TeslaNotice'; import './App.css'; import Header from './components/Header/Header'; import appReducer from './reducers/teslaRangeApp'; const store = createStore(appReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); /** * Top-level component of entire app */ class App extends Component { render() { return ( <Provider store={store}> <div> <Header /> <div className="wrapper"> <form className="tesla-battery"> <h1>Range Per Charge</h1> <TeslaCarContainer /> <TeslaStatsContainer /> <div className="tesla-controls cf"> <TeslaSpeedCounterContainer /> <div className="tesla-climate-container cf"> <TeslaTempCounterContainer /> <TeslaClimateContainer /> </div> <TeslaWheelsContainer /> </div> <TeslaNotice /> </form> </div> </div> </Provider> ); } } export default App;
src/svg-icons/action/settings-cell.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsCell = (props) => ( <SvgIcon {...props}> <path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM16 .01L8 0C6.9 0 6 .9 6 2v16c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V2c0-1.1-.9-1.99-2-1.99zM16 16H8V4h8v12z"/> </SvgIcon> ); ActionSettingsCell = pure(ActionSettingsCell); ActionSettingsCell.displayName = 'ActionSettingsCell'; ActionSettingsCell.muiName = 'SvgIcon'; export default ActionSettingsCell;
ContosoUniversity.Spa.React/ClientApp/src/components/common/Footer.js
alimon808/contoso-university
import React from 'react'; export default function () { return ( <footer className="container"> <p>&copy; 2018 - Contoso University</p> </footer> ); }
packages/material-ui-icons/src/BorderInner.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let BorderInner = props => <SvgIcon {...props}> <path d="M3 21h2v-2H3v2zm4 0h2v-2H7v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zM9 3H7v2h2V3zM5 3H3v2h2V3zm12 0h-2v2h2V3zm2 6h2V7h-2v2zm0-6v2h2V3h-2zm-4 18h2v-2h-2v2zM13 3h-2v8H3v2h8v8h2v-8h8v-2h-8V3zm6 18h2v-2h-2v2zm0-4h2v-2h-2v2z" /> </SvgIcon>; BorderInner = pure(BorderInner); BorderInner.muiName = 'SvgIcon'; export default BorderInner;
docs-ui/components/confirm.stories.js
beeftornado/sentry
import React from 'react'; import {withInfo} from '@storybook/addon-info'; import {action} from '@storybook/addon-actions'; import Confirm from 'app/components/confirm'; import Button from 'app/components/button'; export default { title: 'Core/Buttons/Confirm', }; export const _Confirm = withInfo({ text: 'Component whose child is rendered as the "action" component that when clicked opens the "Confirm Modal"', propTablesExclude: [Button], })(() => ( <div> <Confirm onConfirm={action('confirmed')} message="Are you sure you want to do this?"> <Button priority="primary">Confirm on Button click</Button> </Confirm> </div> ));
src/Thumbnail.js
aparticka/react-bootstrap
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const Thumbnail = React.createClass({ mixins: [BootstrapMixin], propTypes: { alt: React.PropTypes.string, href: React.PropTypes.string, src: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'thumbnail' }; }, render() { let classes = this.getBsClassSet(); if(this.props.href) { return ( <SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </SafeAnchor> ); } else { if(this.props.children) { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> <div className="caption"> {this.props.children} </div> </div> ); } else { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </div> ); } } } }); export default Thumbnail;
0020-flowtype/app/src/index.js
davidwparker/programmingtil-react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
tests/Formsy-spec.js
christianalfoni/formsy-react
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import TestInput from './utils/TestInput'; import TestInputHoc from './utils/TestInputHoc'; import immediate from './utils/immediate'; import sinon from 'sinon'; export default { 'Setting up a form': { 'should expose the users DOM node through an innerRef prop': function (test) { const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInputHoc name="name" innerRef={(c) => { this.name = c; }} /> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = form.name; test.equal(input.methodOnWrappedInstance('foo'), 'foo'); test.done(); }, 'should render a form into the document': function (test) { const form = TestUtils.renderIntoDocument(<Formsy.Form></Formsy.Form>); test.equal(ReactDOM.findDOMNode(form).tagName, 'FORM'); test.done(); }, 'should set a class name if passed': function (test) { const form = TestUtils.renderIntoDocument( <Formsy.Form className="foo"></Formsy.Form>); test.equal(ReactDOM.findDOMNode(form).className, 'foo'); test.done(); }, 'should allow for null/undefined children': function (test) { let model = null; const TestForm = React.createClass({ render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> <h1>Test</h1> { null } { undefined } <TestInput name="name" value={ 'foo' } /> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.deepEqual(model, {name: 'foo'}); test.done(); }); }, 'should allow for inputs being added dynamically': function (test) { const inputs = []; let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {inputs} </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait before adding the input setTimeout(() => { inputs.push(<TestInput name="test" value="" key={inputs.length}/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.ok('test' in model); test.done(); }); }); }, 10); }, 'should allow dynamically added inputs to update the form-model': function (test) { const inputs = []; let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {inputs} </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait before adding the input immediate(() => { inputs.push(<TestInput name="test" key={inputs.length}/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'foo'}}); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(model.test, 'foo'); test.done(); }); }); }); }, 'should allow a dynamically updated input to update the form-model': function (test) { let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { const input = <TestInput name="test" value={this.props.value} />; return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {input} </Formsy.Form>); } }); let form = TestUtils.renderIntoDocument(<TestForm value="foo"/>); // Wait before changing the input immediate(() => { form = TestUtils.renderIntoDocument(<TestForm value="bar"/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(model.test, 'bar'); test.done(); }); }); }); } }, 'validations': { 'should run when the input changes': function (test) { const runRule = sinon.spy(); const notRunRule = sinon.spy(); Formsy.addValidationRule('runRule', runRule); Formsy.addValidationRule('notRunRule', notRunRule); const form = TestUtils.renderIntoDocument( <Formsy.Form> <TestInput name="one" validations="runRule" value="foo"/> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(runRule.calledWith({one: 'bar'}, 'bar', true), true); test.equal(notRunRule.called, false); test.done(); }, 'should allow the validation to be changed': function (test) { const ruleA = sinon.spy(); const ruleB = sinon.spy(); Formsy.addValidationRule('ruleA', ruleA); Formsy.addValidationRule('ruleB', ruleB); class TestForm extends React.Component { constructor(props) { super(props); this.state = {rule: 'ruleA'}; } changeRule() { this.setState({ rule: 'ruleB' }); } render() { return ( <Formsy.Form> <TestInput name="one" validations={this.state.rule} value="foo"/> </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); form.changeRule(); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true); test.done(); }, 'should invalidate a form if dynamically inserted input is invalid': function (test) { const isInValidSpy = sinon.spy(); class TestForm extends React.Component { constructor(props) { super(props); this.state = {showSecondInput: false}; } addInput() { this.setState({ showSecondInput: true }); } render() { return ( <Formsy.Form ref="formsy" onInvalid={isInValidSpy}> <TestInput name="one" validations="isEmail" value="[email protected]"/> { this.state.showSecondInput ? <TestInput name="two" validations="isEmail" value="foo@bar"/> : null } </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); test.equal(form.refs.formsy.state.isValid, true); form.addInput(); immediate(() => { test.equal(isInValidSpy.called, true); test.done(); }); }, 'should validate a form when removing an invalid input': function (test) { const isValidSpy = sinon.spy(); class TestForm extends React.Component { constructor(props) { super(props); this.state = {showSecondInput: true}; } removeInput() { this.setState({ showSecondInput: false }); } render() { return ( <Formsy.Form ref="formsy" onValid={isValidSpy}> <TestInput name="one" validations="isEmail" value="[email protected]"/> { this.state.showSecondInput ? <TestInput name="two" validations="isEmail" value="foo@bar"/> : null } </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); test.equal(form.refs.formsy.state.isValid, false); form.removeInput(); immediate(() => { test.equal(isValidSpy.called, true); test.done(); }); }, 'runs multiple validations': function (test) { const ruleA = sinon.spy(); const ruleB = sinon.spy(); Formsy.addValidationRule('ruleA', ruleA); Formsy.addValidationRule('ruleB', ruleB); const form = TestUtils.renderIntoDocument( <Formsy.Form> <TestInput name="one" validations="ruleA,ruleB" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(ruleA.calledWith({one: 'bar'}, 'bar', true), true); test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true); test.done(); } }, 'should not trigger onChange when form is mounted': function (test) { const hasChanged = sinon.spy(); const TestForm = React.createClass({ render() { return <Formsy.Form onChange={hasChanged}></Formsy.Form>; } }); TestUtils.renderIntoDocument(<TestForm/>); test.equal(hasChanged.called, false); test.done(); }, 'should trigger onChange once when form element is changed': function (test) { const hasChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasChanged}> <TestInput name="foo"/> </Formsy.Form> ); TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}}); test.equal(hasChanged.calledOnce, true); test.done(); }, 'should trigger onChange once when new input is added to form': function (test) { const hasChanged = sinon.spy(); const TestForm = React.createClass({ getInitialState() { return { showInput: false }; }, addInput() { this.setState({ showInput: true }) }, render() { return ( <Formsy.Form onChange={hasChanged}> { this.state.showInput ? <TestInput name="test"/> : null } </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); form.addInput(); immediate(() => { test.equal(hasChanged.calledOnce, true); test.done(); }); }, 'Update a form': { 'should allow elements to check if the form is disabled': function (test) { const TestForm = React.createClass({ getInitialState() { return { disabled: true }; }, enableForm() { this.setState({ disabled: false }); }, render() { return ( <Formsy.Form disabled={this.state.disabled}> <TestInput name="foo"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.isFormDisabled(), true); form.enableForm(); immediate(() => { test.equal(input.isFormDisabled(), false); test.done(); }); }, 'should be possible to pass error state of elements by changing an errors attribute': function (test) { const TestForm = React.createClass({ getInitialState() { return { validationErrors: { foo: 'bar' } }; }, onChange(values) { this.setState(values.foo ? { validationErrors: {} } : { validationErrors: {foo: 'bar'} }); }, render() { return ( <Formsy.Form onChange={this.onChange} validationErrors={this.state.validationErrors}> <TestInput name="foo"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait for update immediate(() => { const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.getErrorMessage(), 'bar'); input.setValue('gotValue'); // Wait for update immediate(() => { test.equal(input.getErrorMessage(), null); test.done(); }); }); }, 'should trigger an onValidSubmit when submitting a valid form': function (test) { let isCalled = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onValidSubmit={isCalled}> <TestInput name="foo" validations="isEmail" value="[email protected]"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm); TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm)); test.equal(isCalled.called,true); test.done(); }, 'should trigger an onInvalidSubmit when submitting an invalid form': function (test) { let isCalled = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onInvalidSubmit={isCalled}> <TestInput name="foo" validations="isEmail" value="foo@bar"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm); TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm)); test.equal(isCalled.called, true); test.done(); } }, 'value === false': { 'should call onSubmit correctly': function (test) { const onSubmit = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onSubmit={onSubmit}> <TestInput name="foo" value={false} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(onSubmit.calledWith({foo: false}), true); test.done(); }, 'should allow dynamic changes to false': function (test) { const onSubmit = sinon.spy(); const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form onSubmit={onSubmit}> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); form.changeValue(); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(onSubmit.calledWith({foo: false}), true); test.done(); }, 'should say the form is submitted': function (test) { const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" value={true} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.isFormSubmitted(), false); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(input.isFormSubmitted(), true); test.done(); }, 'should be able to reset the form to its pristine state': function (test) { const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); test.equal(input.getValue(), true); form.changeValue(); test.equal(input.getValue(), false); formsyForm.reset(); test.equal(input.getValue(), true); test.done(); }, 'should be able to reset the form using custom data': function (test) { const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); test.equal(input.getValue(), true); form.changeValue(); test.equal(input.getValue(), false); formsyForm.reset({ foo: 'bar' }); test.equal(input.getValue(), 'bar'); test.done(); } }, 'should be able to reset the form to empty values': function (test) { const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" value="42" type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); formsyForm.reset({ foo: '' }); test.equal(input.getValue(), ''); test.done(); }, '.isChanged()': { 'initially returns false': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); test.equal(form.isChanged(), false); test.equal(hasOnChanged.called, false); test.done(); }, 'returns true when changed': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(form.isChanged(), true); test.equal(hasOnChanged.calledWith({one: 'bar'}), true); test.done(); }, 'returns false if changes are undone': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(hasOnChanged.calledWith({one: 'bar'}, true), true); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'foo'}}); test.equal(form.isChanged(), false); test.equal(hasOnChanged.calledWith({one: 'foo'}, false), true); test.done(); } } };
packages/material-ui-icons/src/People.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" /></g> , 'People');
src/TabPane.js
jontewks/react-bootstrap
import React from 'react'; import deprecationWarning from './utils/deprecationWarning'; import Tab from './Tab'; const TabPane = React.createClass({ componentWillMount() { deprecationWarning( 'TabPane', 'Tab', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { return ( <Tab {...this.props} /> ); } }); export default TabPane;
src/server.js
lolilukia/Personal-gallery
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://localhost:' + server.get('port')); if (process.send) { process.send('online'); } });
packages/wix-style-react/src/MessageBox/docs/AlertExamples/Scrollable.js
wix/wix-style-react
/* eslint-disable react/prop-types */ import React from 'react'; import { MessageBoxFunctionalLayout } from 'wix-style-react'; export default () => ( <MessageBoxFunctionalLayout title="Interruption Message" confirmText="Action" maxHeight="200px" theme="blue" dataHook="alert-scrollable" > <div> This is a generic message. No harm done, but really needed to interrupt you. </div> <div>It has multiple lines and limited max height</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> <div>and some are rows hidden</div> </MessageBoxFunctionalLayout> );
src/main/script/EntryList.js
krujos/willitconnect
import PropTypes from 'prop-types'; import React from 'react'; import StatefulEntry from './Entry'; const EntryList = (props) => { const entryNodes = props.data.map(entry => { return ( <StatefulEntry key={entry.id} onSubmit={props.onSubmit} onChange={props.onChange} {...entry} /> ); }).reverse(); return ( <div className="entryList"> {entryNodes} </div> ); }; export default EntryList; EntryList.propTypes = { data: PropTypes.array.isRequired, onChange: PropTypes.func, onSubmit: PropTypes.func, }; EntryList.defaultProps = { data: [], };
js/App/Components/Schedule/SubViews/TextRowWrapper.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : 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. * * Telldus Live! app 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 Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import { View } from '../../../../BaseComponents'; type Props = { children: string, style?: Object, appLayout: Object, }; export default class TextRowWrapper extends View<null, Props, null> { static propTypes = { children: PropTypes.node.isRequired, style: PropTypes.object, }; render(): React$Element<any> { const { children, style, appLayout } = this.props; const defaultStyle = this._getDefaultStyle(appLayout); return ( <View style={[defaultStyle, style]}> {children} </View> ); } _getDefaultStyle = (appLayout: Object): Object => { const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; return { justifyContent: 'center', backgroundColor: 'transparent', alignItems: 'flex-start', width: deviceWidth * 0.586666667, paddingLeft: deviceWidth * 0.101333333, paddingRight: 10, paddingVertical: 5, }; }; }
client/containers/shell.js
vidi-insights/vidi-dashboard
'use strict' import React from 'react' import {connect} from 'react-redux' import {Header, Footer} from '../components/index' export const Shell = React.createClass({ render () { const handleToggle = this.handleToggle const {children, isLoggedIn} = this.props return ( <div className="shell"> <Header showMenu={isLoggedIn}/> <div className={'page-wrapper'}>{children}</div> <Footer /> </div> ) } }) export default connect((state) => { return { isLoggedIn: state.auth.isLoggedIn } })(Shell)
docs/app/Examples/elements/Button/GroupVariations/ButtonGroupEqualWidthExample.js
jcarbo/stardust
import React from 'react' import { Button, Divider } from 'stardust' const ButtonGroupEqualWidthExample = () => ( <div> <Button.Group widths='5'> <Button>Overview</Button> <Button>Specs</Button> <Button>Warranty</Button> <Button>Reviews</Button> <Button>Support</Button> </Button.Group> <Divider /> <Button.Group widths='3'> <Button>Overview</Button> <Button>Specs</Button> <Button>Support</Button> </Button.Group> </div> ) export default ButtonGroupEqualWidthExample
docs/app/Examples/modules/Embed/States/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const EmbedStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Active' description='An embed can be active.' examplePath='modules/Embed/States/EmbedExampleActive' /> </ExampleSection> ) export default EmbedStatesExamples
ui/src/js/selfPlantOverview/SelfPlantOverviewPage.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import React, { Component } from 'react'; import { Map, Marker, TileLayer, useMap } from 'react-leaflet'; import { browserHistory } from 'react-router'; import NotificationSystem from 'react-notification-system'; import Notification from '../common/components/Notification'; import DateField from '../common/components/DateField'; import IconButton from '../common/components/IconButton'; import FileChooser from '../common/components/FileChooser'; import { getTextForSelectedLanguage } from '../common/language/LanguageHelper'; require('./selfPlantOverview.less'); export default class SelfPlantOverviewPage extends Component { constructor() { super(); this.state = { edit: false, showEditMap: true, selfPlantData: { latitude: 0, longitude: 0, plantedOn: new Date().getTime(), description: '', amount: 1, imageName: '', treeTypeId: 1, treeTypeName: '', }, imageFile: null, treeTypes: [], treePosition: [51.499807, 11.956521], trees: [], myTree: { latitude: 0, longitude: 0 }, treeId: null, allowEdit: localStorage.getItem('isAdmin') === 'true', }; } componentDidMount() { var that = this; // this is a little hack to assure both leaflet maps(for edit and non-edit) are rendered correctly // on initial rendering both maps have to be displayed so that leaflet can render the correct tiles // surprisingly 1ms is enough... setTimeout(() => { that.setState({showEditMap: false}); }, 1); axios .get('http://localhost:8081/treeTypes') .then(function (response) { var result = response.data; result.splice(result.length - 1, 0, result.splice(0, 1)[0]); that.setState({ treeTypes: result }); }) .catch(function (response) { if (response instanceof Error) { console.error('Error', response.message); } else { console.error(response.data); console.error(response.status); console.error(response.headers); console.error(response.config); } }); axios .get('http://localhost:8081/trees/selfPlanted') .then(function (response) { var result = response.data; that.setState({ trees: result }); }) .catch(function (error) { that.refs.notification.handleError(error); }); that.getMyTree(); } getMyTree() { var that = this; axios .get('http://localhost:8081/tree/' + this.props.params.treeId) .then(function (response) { var result = response.data; that.setState({ myTree: { latitude: result.latitude, longitude: result.longitude, }, selfPlantData: { latitude: result.latitude, longitude: result.longitude, plantedOn: result.plantedOn, description: result.description, amount: result.amount, imageName: result.imagePath, treeTypeId: result.treeType.id, treeTypeName: result.treeType.name, }, treeId: result.id, allowEdit: that.state.allowEdit || localStorage.getItem('username') === result.owner.name, treeOwner: result.owner.name, }); that.refs.description.value = result.description; }) .catch(function (error) { that.refs.notification.handleError(error); }); } updatePlantedOn(value) { this.state.selfPlantData.plantedOn = value; this.forceUpdate(); } updateAmount(event) { this.state.selfPlantData.amount = event.target.value; this.forceUpdate(); } updateImage(imageName, file) { this.state.selfPlantData.imageName = imageName; this.state.imageFile = file; this.forceUpdate(); } updateTreeType(event) { this.state.selfPlantData.treeTypeId = event.target.value; this.forceUpdate(); } sendSelfPlantedTree() { if (localStorage.getItem('jwt') == null || localStorage.getItem('jwt') == '') { this.refs.notification.addNotification(counterpart.translate('NO_AUTH_USER_TITLE'), counterpart.translate('NO_AUTH_USER_TEXT'), 'error'); } else { var that = this; var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt'), }, }; this.state.selfPlantData.description = this.refs.description.value; axios .put('http://localhost:8081/plantSelf?id=' + this.state.treeId, this.state.selfPlantData, config) .then(function (response) { if (that.state.imageFile != null) { var data = new FormData(); data.append('treeId', response.data); data.append('file', that.state.imageFile); axios .post('http://localhost:8081/plantSelf/upload', data, config) .then(function (response) { that.refs.notification.addNotification(counterpart.translate('PLANTING_CREATED'), '', 'success'); that.setState({ edit: false, showEditMap: false }); that.forceUpdate(); location.reload(); }) .catch(function (response) { if (response instanceof Error) { console.error('Error', response.message); } else { console.error(response.data); console.error(response.status); console.error(response.headers); console.error(response.config); } that.setState({ edit: false, showEditMap: false }); }); } else { that.refs.notification.addNotification(counterpart.translate('PLANTING_CREATED'), '', 'success'); that.setState({ edit: false, showEditMap: false }); location.reload(); } }) .catch(function (response) { that.refs.notification.addNotification(counterpart.translate('ERROR'), counterpart.translate('TRY_AGAIN'), 'error'); if (response instanceof Error) { console.error('Error', response.message); } else { console.error(response.data); console.error(response.status); console.error(response.headers); console.error(response.config); } that.setState({ edit: false }); }); } } startEdit() { this.setState({ edit: true, showEditMap: true }); } updateTreePositionFromMapClick(event) { if (this.state.edit) { this.state.selfPlantData.latitude = parseFloat(event.latlng.lat); this.state.selfPlantData.longitude = parseFloat(event.latlng.lng); this.state.myTree.latitude = parseFloat(event.latlng.lat); this.state.myTree.longitude = parseFloat(event.latlng.lng); this.refs.marker.leafletElement._latlng.lat = event.latlng.lat; this.refs.marker.leafletElement._latlng.lng = event.latlng.lng; this.forceUpdate(); } } updateTreePositionFromMarkerDrag() { if (this.state.edit) { this.state.selfPlantData.latitude = parseFloat(this.refs.marker.leafletElement._latlng.lat); this.state.selfPlantData.longitude = parseFloat(this.refs.marker.leafletElement._latlng.lng); this.state.myTree.latitude = parseFloat(this.refs.marker.leafletElement._latlng.lat); this.state.myTree.longitude = parseFloat(this.refs.marker.leafletElement._latlng.lng); this.forceUpdate(); } } openDeleteConfirmation() { this.refs.notificationSystem.addNotification({ title: counterpart.translate('WARNING') + '!', position: 'tc', autoDismiss: 0, message: counterpart.translate('DELETE_SELFPLANTING_CONFIRMATION_TEXT'), level: 'warning', children: ( <div className="delete-confirmation align-center"> <button>{counterpart.translate('ABORT')}</button> <button onClick={() => { this.deleteTree(); }} > OK </button> </div> ), }); } deleteTree() { var config = { headers: { 'X-AUTH-TOKEN': localStorage.getItem('jwt'), }, }; var that = this; axios .delete('http://localhost:8081/plantSelf?treeId=' + this.state.treeId, config) .then(function (response) { browserHistory.push('/user/' + encodeURIComponent(that.state.treeOwner)); }) .catch(function (error) { that.refs.notification.handleError(error); }); } render() { let that = this; let myIcon = L.divIcon({ className: 'glyphicon glyphicon-tree-deciduous' }); let myTreeIcon = L.divIcon({ className: 'glyphicon glyphicon-tree-deciduous my-tree' }); var confirmBoxStyle = { Containers: { DefaultStyle: { zIndex: 11000, }, tc: { top: '50%', bottom: 'auto', margin: '0 auto', left: '50%', }, }, }; return ( <div className="container paddingTopBottom15 selfPlantOverview"> <div className="row"> <div className="col-md-12"> <h1> {counterpart.translate('COMMUNITY_TREE')} <div className={this.state.allowEdit ? 'delete-btn ' : 'no-display '}> <IconButton glyphIcon="glyphicon-trash" text="" onClick={this.openDeleteConfirmation.bind(this)} /> </div> <div className={this.state.allowEdit && !this.state.edit ? '' : 'no-display '}> <IconButton glyphIcon="glyphicon-pencil" text="" onClick={this.startEdit.bind(this)} /> </div> </h1> </div> </div> <div className={'row ' + (this.state.edit ? '' : 'no-display')}> <div className="form-group col-md-4"> <label htmlFor="when">{counterpart.translate('DATE')}:</label> <DateField id="when" date={this.state.selfPlantData.plantedOn} updateDateValue={this.updatePlantedOn.bind(this)} noFuture="true" /> </div> <div className="form-group col-md-8"> <label htmlFor="howmuch"> {counterpart.translate('NUMBER')}:&nbsp;{this.state.selfPlantData.amount} </label> <input className="tree-slider" type="range" min="1" max={localStorage.getItem('isAdmin') === 'true' ? 10000 : 10} value={this.state.selfPlantData.amount} step="1" onChange={this.updateAmount.bind(this)} /> <br /> <span>{counterpart.translate('HOW_MANY_HINT')}</span> </div> </div> <div className={'row ' + (this.state.edit ? '' : 'no-display')}> <div className="form-group col-md-4"> <label htmlFor="photo">{counterpart.translate('FOTO')}:</label> <FileChooser id="photo" updateFile={this.updateImage.bind(this)} /> </div> <div className="form-group col-md-8"> <label htmlFor="treeType">{counterpart.translate('TREETYPE')}:</label> <select id="treeType" className="form-control" onChange={this.updateTreeType.bind(this)} ref="select"> {this.state.treeTypes.map(function (treeType, i) { if (treeType.name != 'Default') { if (treeType.id === that.state.selfPlantData.treeTypeId) { return ( <option value={treeType.id} key={i} selected="selected"> {getTextForSelectedLanguage(treeType.name)} </option> ); } else { return ( <option value={treeType.id} key={i}> {getTextForSelectedLanguage(treeType.name)} </option> ); } } else { if (treeType.id === that.state.selfPlantData.treeTypeId) { return ( <option value={treeType.id} key={i} selected="selected"> {counterpart.translate('OTHER')} </option> ); } else { return ( <option value={treeType.id} key={i}> {counterpart.translate('OTHER')} </option> ); } } })} </select> </div> </div> <div className={'row ' + (this.state.showEditMap ? '' : 'no-display')}> <div className="form-group col-md-4"> <label htmlFor="description">{counterpart.translate('SHORT_DESCRIPTION')}:</label> <div> <textarea rows="4" cols="50" ref="description" /> </div> </div> <div className="col-md-8"> <label htmlFor="all-self-planted-edit-map">{counterpart.translate('TREE_LOCATION')}:</label> <Map id="all-self-planted-edit-map" center={[this.state.myTree.latitude, this.state.myTree.longitude]} zoom={10} onClick={this.updateTreePositionFromMapClick.bind(this)} > <TileLayer url="https://{s}.tile.osm.org/{z}/{x}/{y}.png" attribution='&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' /> <Marker position={[this.state.myTree.latitude, this.state.myTree.longitude]} ref="marker" draggable={this.state.edit} icon={myTreeIcon} onDragEnd={this.updateTreePositionFromMarkerDrag.bind(this)} /> {this.state.trees.map(function (tree, i) { if (tree.latitude && tree.longitude) { if (tree.id != that.props.params.treeId) { return <Marker key={i} position={[tree.latitude, tree.longitude]} ref={'marker-' + i} icon={myIcon} />; } } else { return ''; } })} </Map> </div> </div> <div className={'row ' + (this.state.edit ? '' : 'no-display')}> <div className="col-md-12 align-left"> <IconButton text="Planzung aktualisieren" glyphIcon="glyphicon-tree-deciduous" onClick={this.sendSelfPlantedTree.bind(this)} /> </div> </div> <div className={'row ' + (this.state.edit ? 'no-display' : '')}> <div className="col-md-4"> <div className={'row ' + (this.state.edit ? 'no-display' : 'no-padding')}> <div className="col-md-12 center"> <img height="150px" src={'http://localhost:8081/tree/image/' + encodeURIComponent(this.state.selfPlantData.imageName) + '/935/935'} /> </div> <div className="col-md-12 tree-description"><i>{this.state.selfPlantData.description}</i></div> <div className="col-md-12"><b>{counterpart.translate('DATE')}: </b> {new Date(this.state.selfPlantData.plantedOn).toLocaleDateString()}</div> <div className="col-md-12"><b>{counterpart.translate('NUMBER')}: </b>{this.state.selfPlantData.amount}</div> <div className="col-md-12"><b>{counterpart.translate('TREETYPE')}: </b>{getTextForSelectedLanguage(this.state.selfPlantData.treeTypeName)}</div> </div> </div> <div className="col-md-8"> <Map id="all-self-planted-map" center={[this.state.myTree.latitude, this.state.myTree.longitude]} zoom={10} onClick={this.updateTreePositionFromMapClick.bind(this)} > <TileLayer url="https://{s}.tile.osm.org/{z}/{x}/{y}.png" attribution='&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' /> <Marker position={[this.state.myTree.latitude, this.state.myTree.longitude]} ref="marker" draggable={this.state.edit} icon={myTreeIcon} onDragEnd={this.updateTreePositionFromMarkerDrag.bind(this)} /> {this.state.trees.map(function (tree, i) { if (tree.latitude && tree.longitude) { if (tree.id != that.props.params.treeId) { return <Marker key={i} position={[tree.latitude, tree.longitude]} ref={'marker-' + i} icon={myIcon} />; } } else { return ''; } })} </Map> </div> </div> <Notification ref="notification" /> <NotificationSystem ref="notificationSystem" style={confirmBoxStyle} /> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
fields/types/email/EmailField.js
everisARQ/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; /* TODO: - gravatar - validate email address */ module.exports = Field.create({ displayName: 'EmailField', renderField () { return ( <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" type="email" /> ); }, renderValue () { return this.props.value ? ( <FormInput noedit href={'mailto:' + this.props.value}>{this.props.value}</FormInput> ) : ( <FormInput noedit>(not set)</FormInput> ); }, });
Examples/TabsExample/src/routes.js
Wolox/react-native-renavigate
import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; import { actionCreators as navigationActions } from 'react-native-renavigate'; import PostDetailContainer from './PostDetailContainer'; import PostListContainer from './PostListContainer'; import EmptyView from './EmptyView'; const navButtonStyle = { padding: 5, color: 'blue' }; const titleStyle = { fontWeight: 'bold' }; export default { DETAIL: (params) => ({ component: PostDetailContainer, params, leftButton: (dispatch) => { const goBack = () => { dispatch(navigationActions.pop()); }; return ( <TouchableOpacity onPress={goBack}> <Text style={navButtonStyle}>Back</Text> </TouchableOpacity> ); }, rightButton: () => { return <Text style={navButtonStyle}>FAV</Text>; }, title: () => { return <Text style={[navButtonStyle, titleStyle]}>{ params.title }</Text>; } }), LIST: (params) => ({ component: PostListContainer, params, title: () => { return <Text style={[titleStyle, navButtonStyle]}>YOUR POSTS</Text>; } }), EMPTY_VIEW: (params) => ({ component: EmptyView, params, title: () => { return <Text style={[titleStyle, navButtonStyle]}>EMPTY VIEW</Text>; } }) };
src/client/components/list/button/FollowButton.js
DBCDK/content-first
import React from 'react'; import {connect} from 'react-redux'; import {getListByIdSelector, CUSTOM_LIST} from '../../../redux/list.reducer'; import {OPEN_MODAL} from '../../../redux/modal.reducer'; import Button from '../../base/Button'; import Icon from '../../base/Icon'; import T from '../../base/T'; import {withFollow} from '../../hoc/Follow'; const getListById = getListByIdSelector(); export const FollowButton = ({ disabled = false, allowFollow, isLoggedIn, isFollowing, follow, unFollow, requireLogin, className, style }) => { if (!allowFollow) { return null; } return ( <Button className={className} disabled={disabled} type="link2" style={{ color: isFollowing ? 'var(--de-york)' : 'var(--petroleum)', textDecoration: 'none', ...style }} onClick={() => { if (!isLoggedIn) { return requireLogin(); } if (isFollowing) { return unFollow(); } return follow(); }} data-cy="follow-btn" > <span className="align-middle"> <Icon name="playlist_add" className="mr-1 align-middle" /> <T component="list" name={isFollowing ? 'followingList' : 'followList'} /> </span> </Button> ); }; const mapStateToProps = (state, ownProps) => { const list = getListById(state, {_id: ownProps._id}); return { allowFollow: list.type === CUSTOM_LIST, isLoggedIn: state.userReducer.isLoggedIn }; }; export const mapDispatchToProps = dispatch => ({ requireLogin: () => { dispatch({ type: OPEN_MODAL, modal: 'login', context: { title: <T component="list" name={'followList'} />, reason: <T component="list" name={'loginFollowModalDescription'} /> } }); } }); export default connect( mapStateToProps, mapDispatchToProps )(withFollow(FollowButton));
src/icons/image.js
markdyousef/zen-editor
import React from 'react'; export default ({ ...props }) => { return ( <svg {...props} width="16" height="16" viewBox="0 0 16 16"> <g> <path d="M14.39,2.31H1.61c-0.83,0-1.5,0.68-1.5,1.5v8.41c0,0.83,0.67,1.5,1.5,1.5h12.78c0.49,0,0.93-0.23,1.19-0.6 c0.08-0.09,0.14-0.19,0.18-0.3c0.09-0.18,0.13-0.39,0.13-0.6V3.81C15.89,2.99,15.22,2.31,14.39,2.31z M1.11,3.81 c0-0.27,0.22-0.5,0.5-0.5h12.78c0.28,0,0.5,0.23,0.5,0.5v7.96l-4.01-4.02c-0.14-0.14-0.36-0.15-0.51-0.02L7.96,9.77L5.25,7.08 C5.12,6.95,4.91,6.93,4.76,7.04L1.11,9.8V3.81z M1.61,12.72c-0.28,0-0.5-0.23-0.5-0.5v-1.47l3.84-2.91l2.7,2.68l2.21,2.2H1.61z M14.39,12.72h-3.46L8.49,10.3l2.1-1.78l4.09,4.1C14.6,12.68,14.5,12.72,14.39,12.72z" /> </g> <g> <path d="M15.76,12.82c0,0.09-0.03,0.18-0.1,0.25c-0.02,0.02-0.05,0.04-0.08,0.05C15.66,13.03,15.72,12.93,15.76,12.82z" /> </g> <g> <path d="M12.718,7.153c-0.872,0-1.582-0.71-1.582-1.583c0-0.873,0.71-1.583,1.582-1.583c0.873,0,1.583,0.71,1.583,1.583 C14.301,6.443,13.591,7.153,12.718,7.153z M12.718,4.738c-0.459,0-0.832,0.374-0.832,0.833c0,0.459,0.373,0.833,0.832,0.833 s0.833-0.374,0.833-0.833C13.551,5.111,13.177,4.738,12.718,4.738z" /> </g> </svg> ); };
actor-apps/app-web/src/app/components/ActivitySection.react.js
liqk2014/actor-platform
import React from 'react'; import classNames from 'classnames'; import { ActivityTypes } from 'constants/ActorAppConstants'; //import ActivityActionCreators from 'actions/ActivityActionCreators'; import ActivityStore from 'stores/ActivityStore'; import UserProfile from 'components/activity/UserProfile.react'; import GroupProfile from 'components/activity/GroupProfile.react'; const getStateFromStores = () => { return { activity: ActivityStore.getActivity(), isOpen: ActivityStore.isOpen() }; }; class ActivitySection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { ActivityStore.removeChangeListener(this.onChange); } render() { const activity = this.state.activity; if (activity !== null) { const activityClassName = classNames('activity', { 'activity--shown': this.state.isOpen }); let activityBody; switch (activity.type) { case ActivityTypes.USER_PROFILE: activityBody = <UserProfile user={activity.user}/>; break; case ActivityTypes.GROUP_PROFILE: activityBody = <GroupProfile group={activity.group}/>; break; default: } return ( <section className={activityClassName}> {activityBody} </section> ); } else { return null; } } onChange = () => { this.setState(getStateFromStores()); }; } export default ActivitySection;
src/components/Team.js
ccoode/timer
import React from 'react' import classNames from 'classnames' import Meta from './Meta' import Control from './Control' import Clock from './Clock' function Team(props) { const divClass = classNames({ team: true, hide: props.hide, }) return ( <div className={divClass}> <Meta right={props.right} teamName={props.name} thought={props.thought} hide={props.hideAll} /> <Clock timeout={props.timeout} /> <Control controlFns={props.controlFns} running={props.running} end={props.end} /> </div> ) } export default Team
client/src/app/components/ribbon/SmallBreadcrumbs.js
zraees/sms-project
import React from 'react' import {connect} from 'react-redux' import Msg from '../i18n/Msg' class SmallBreadcrumbs extends React.Component { render() { return ( <ol className="breadcrumb"> { this.props.items.map((it, idx)=> ( <li key={it + idx}><Msg phrase={it}/></li> )) } </ol> ) } } const mapStateToProps = (state, ownProps) => { const {navigation, routing}= state; const route = routing.locationBeforeTransitions.pathname; const titleReducer = (chain, it)=> { if (it.route == route) { chain.push(it.title) } else if (it.items) { it.items.reduce(titleReducer, chain); } return chain }; const items = navigation.items.reduce(titleReducer, ['Home']); return {items} }; export default connect(mapStateToProps)(SmallBreadcrumbs)
front/app/app/rh-components/rh-Panel.js
nudoru/React-Starter-2-app
import React from 'react'; const Panel = (props) => { let panelClass = ['rh-panel'], header, footer; if (props.title || props.icon || props.utilityButtons) { header = <PanelHeader {...props}/>; } if (props.footerNote || props.actionButtons) { footer = <PanelFooter {...props}/>; } return (<section className={panelClass.join(' ')}> {header} <div className="rh-panel-content"> {props.children} </div> {footer} </section>); }; export default Panel; export const PanelHeader = ({title, icon, utilityButtons}) => { let headerIcon = icon ? <div className="rh-panel-header-icon"><i className={'fa fa-' + icon}/> </div> : null; // TODO apply key to utility buttons return (<div className="rh-panel-header"> {headerIcon} <div className="rh-panel-header-label"> <h1>{title}</h1> </div> <div className="rh-panel-header-buttons"> {utilityButtons ? utilityButtons.map(b => b) : null} </div> </div>); }; export const PanelFooter = ({footerNote, actionButtons}) => { // TODO apply key to action buttons return (<div className="rh-panel-footer"> <h1>{footerNote}</h1> <div className="rh-panel-footer-buttons"> {actionButtons ? actionButtons.map(b => b) : null} </div> </div>); };
components/selectionBlock/selectionBlock.js
Travix-International/travix-ui-kit
import classnames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { getDataAttributes } from '../_helpers'; const SelectionBlock = (props) => { const { align = 'center', children, className, dataAttrs = {}, icon, logo, logoLabel, subtitle, title, type = 'horizontal', } = props; const logoSection = !logo ? null : ( <div className="ui-selection-block__logo"> <span className="ui-selection-block__logo-label"> {logoLabel} </span> {logo} </div> ); const iconSection = !icon ? null : ( <div className="ui-selection-block__icon"> {icon} </div> ); const classes = classnames(className, 'ui-selection-block', { 'ui-selection-block_vertical': type === 'vertical', [`ui-selection-block_align-${align}`]: true, }); return ( <div className={classes} {...getDataAttributes(dataAttrs)} > <div className="ui-selection-block__section"> <header className="ui-selection-block__header"> <div className="ui-selection-block__titles"> {iconSection} <h2 className="ui-selection-block__title"> {title} </h2> <h5 className="ui-selection-block__subtitle"> {subtitle} </h5> </div> {logoSection} </header> <div className="ui-selection-block__body"> {children} </div> </div> {logoSection} </div> ); }; SelectionBlock.propTypes = { /** * The title section align. */ align: PropTypes.oneOf(['start', 'center', 'end']), /** * Content that will be wrapped by SelectionBlock */ children: PropTypes.node, /** * Specify a CSS class */ className: PropTypes.string, /** * Data attribute. You can use it to set up any custom data-* attribute. */ dataAttrs: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object, ]), /** * The icon for title section. */ icon: PropTypes.node, /** * The selection block logo. */ logo: PropTypes.node, /** * The logo label. */ logoLabel: PropTypes.string, /** * The selection block subtitle. */ subtitle: PropTypes.string, /** * The selection block title. */ title: PropTypes.string, /** * The selection block type. */ type: PropTypes.oneOf(['vertical', 'horizontal']), }; export default SelectionBlock;
client/src/components/dashboard/profile/utils/trash-look-three.js
mikelearning91/seeme-starter
import React, { Component } from 'react'; import Modal from 'react-modal'; import MdDelete from 'react-icons/lib/md/delete'; const cookie = require('react-cookie') const axios = require('axios'); class TrashLookThree extends React.Component { constructor(props) { super(props); this.trashLook = this.trashLook.bind(this); } trashLook() { const user = cookie.load('user'); const emailQuery = user.email; const lookId = user.looks[2]._id; console.log(lookId) axios.put('https://seemedate.herokuapp.com/api/see/delete-look', { emailQuery: emailQuery, lookId: lookId }, { headers: { Authorization: cookie.load('token') } }) .then((response) => { cookie.save('token', response.data.token, { path: '/' }); cookie.save('user', response.data.user, { path: '/' }); this.props.remove(); // window.location.reload() }) .catch((error) => { console.log(error); }); } render() { return ( <div> <button className="trash-look" onClick={this.trashLook}><MdDelete /></button> </div> ); } } export default TrashLookThree;
src/routes.js
RockingChewee/react-redux-building-applications
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/home/HomePage'; import AboutPage from './components/about/AboutPage'; import CoursesPage from './components/course/CoursesPage'; // Linting warning is thrown here due to the fact that ManageCoursePage is exported as a default export (for app) and as a named export (for testing). import ManageCoursePage from './components/course/ManageCoursePage'; //eslint-disable-line import/no-named-as-default export default ( /* Always load the App component and then pass the nested items as "children" to the App based on the routing. */ <Route path="/" component={App}> {/* If someone goes to /, we will load the HomePage. */} <IndexRoute component={HomePage} /> <Route path="courses" component={CoursesPage} /> <Route path="course" component={ManageCoursePage} /> <Route path="course/:id" component={ManageCoursePage} /> <Route path="about" component={AboutPage} /> </Route> );
src/views/HomeView/HomeView.js
oldsaratov/postcards-spa
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import postcardsActions from 'redux/modules/postcards/actions'; import PostcardBox from 'components/PostcardBox/PostcardBox'; const mapStateToProps = (state) => ({ postcards: state.postcards }); export class HomeView extends React.Component { constructor (props) { super(props); } componentDidMount () { const { dispatch } = this.props; dispatch(postcardsActions.fetch()); } render () { let { postcards } = this.props; return ( <div className='container text-center'> <div className='row'> <div className='col-xs-2 col-xs-offset-5'> { _.map(postcards.items, postcard => <PostcardBox key={postcard.id} postcard={postcard} />) } </div> </div> </div> ); } } HomeView.propTypes = { dispatch: React.PropTypes.func.isRequired, postcards: React.PropTypes.object.isRequired }; export default connect(mapStateToProps)(HomeView);
monkey/monkey_island/cc/ui/src/components/report-components/zerotrust/EventsModal.js
guardicore/monkey
import React from 'react'; import {Modal} from 'react-bootstrap'; import EventsTimeline from './EventsTimeline'; import * as PropTypes from 'prop-types'; import saveJsonToFile from '../../utils/SaveJsonToFile'; import EventsModalButtons from './EventsModalButtons'; import AuthComponent from '../../AuthComponent'; import Pluralize from 'pluralize'; import SkippedEventsTimeline from './SkippedEventsTimeline'; const FINDING_EVENTS_URL = '/api/zero-trust/finding-event/'; export default class EventsModal extends AuthComponent { constructor(props) { super(props); } render() { return ( <div> <Modal show={this.props.showEvents} onHide={() => this.props.hideCallback()}> <Modal.Body> <h3> <div className="text-center">Events</div> </h3> <hr/> <p> There {Pluralize('is', this.props.event_count)} { <div className={'badge badge-primary'}>{this.props.event_count}</div> } {Pluralize('event', this.props.event_count)} associated with this finding. { <div className={'badge badge-primary'}> {this.props.latest_events.length + this.props.oldest_events.length} </div> } {Pluralize('is', this.props.event_count)} displayed below. All events can be exported using the Export button. </p> {this.props.event_count > 5 ? this.renderButtons() : null} <EventsTimeline events={this.props.oldest_events}/> {this.props.event_count > this.props.latest_events.length+this.props.oldest_events.length ? this.renderSkippedEventsTimeline() : null} <EventsTimeline events={this.props.latest_events}/> {this.renderButtons()} </Modal.Body> </Modal> </div> ); } renderSkippedEventsTimeline(){ return <div className={'skipped-events-timeline'}> <SkippedEventsTimeline skipped_count={this.props.event_count - this.props.latest_events.length + this.props.oldest_events.length}/> </div> } renderButtons() { return <EventsModalButtons onClickClose={() => this.props.hideCallback()} onClickExport={() => { let full_url = FINDING_EVENTS_URL + this.props.finding_id; this.authFetch(full_url).then(res => res.json()).then(res => { const dataToSave = res.events_json; const filename = this.props.exportFilename; saveJsonToFile(dataToSave, filename); }); }}/>; } } EventsModal.propTypes = { showEvents: PropTypes.bool, events: PropTypes.array, hideCallback: PropTypes.func };
node_modules/antd/es/transfer/list.js
prodigalyijun/demo-by-antd
import _defineProperty from 'babel-runtime/helpers/defineProperty'; 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 { findDOMNode } from 'react-dom'; import classNames from 'classnames'; import Animate from 'rc-animate'; import PureRenderMixin from 'rc-util/es/PureRenderMixin'; import assign from 'object-assign'; import Checkbox from '../checkbox'; import Search from './search'; import Item from './item'; import triggerEvent from '../_util/triggerEvent'; function noop() {} function isRenderResultPlainObject(result) { return result && !React.isValidElement(result) && Object.prototype.toString.call(result) === '[object Object]'; } var TransferList = function (_React$Component) { _inherits(TransferList, _React$Component); function TransferList(props) { _classCallCheck(this, TransferList); var _this = _possibleConstructorReturn(this, (TransferList.__proto__ || Object.getPrototypeOf(TransferList)).call(this, props)); _this.handleSelect = function (selectedItem) { var checkedKeys = _this.props.checkedKeys; var result = checkedKeys.some(function (key) { return key === selectedItem.key; }); _this.props.handleSelect(selectedItem, !result); }; _this.handleFilter = function (e) { _this.props.handleFilter(e); if (!e.target.value) { return; } // Manually trigger scroll event for lazy search bug // https://github.com/ant-design/ant-design/issues/5631 _this.triggerScrollTimer = setTimeout(function () { var listNode = findDOMNode(_this).querySelectorAll('.ant-transfer-list-content')[0]; if (listNode) { triggerEvent(listNode, 'scroll'); } }, 0); }; _this.handleClear = function () { _this.props.handleClear(); }; _this.matchFilter = function (text, item) { var _this$props = _this.props, filter = _this$props.filter, filterOption = _this$props.filterOption; if (filterOption) { return filterOption(filter, item); } return text.indexOf(filter) >= 0; }; _this.renderItem = function (item) { var _this$props$render = _this.props.render, render = _this$props$render === undefined ? noop : _this$props$render; var renderResult = render(item); var isRenderResultPlain = isRenderResultPlainObject(renderResult); return { renderedText: isRenderResultPlain ? renderResult.value : renderResult, renderedEl: isRenderResultPlain ? renderResult.label : renderResult }; }; _this.state = { mounted: false }; return _this; } _createClass(TransferList, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; this.timer = setTimeout(function () { _this2.setState({ mounted: true }); }, 0); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timer); clearTimeout(this.triggerScrollTimer); } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return PureRenderMixin.shouldComponentUpdate.apply(this, args); } }, { key: 'getCheckStatus', value: function getCheckStatus(filteredDataSource) { var checkedKeys = this.props.checkedKeys; if (checkedKeys.length === 0) { return 'none'; } else if (filteredDataSource.every(function (item) { return checkedKeys.indexOf(item.key) >= 0; })) { return 'all'; } return 'part'; } }, { key: 'render', value: function render() { var _this3 = this; var _props = this.props, prefixCls = _props.prefixCls, dataSource = _props.dataSource, titleText = _props.titleText, checkedKeys = _props.checkedKeys, lazy = _props.lazy, _props$body = _props.body, body = _props$body === undefined ? noop : _props$body, _props$footer = _props.footer, footer = _props$footer === undefined ? noop : _props$footer, showSearch = _props.showSearch, style = _props.style, filter = _props.filter, searchPlaceholder = _props.searchPlaceholder, notFoundContent = _props.notFoundContent, itemUnit = _props.itemUnit, itemsUnit = _props.itemsUnit, onScroll = _props.onScroll; // Custom Layout var footerDom = footer(assign({}, this.props)); var bodyDom = body(assign({}, this.props)); var listCls = classNames(prefixCls, _defineProperty({}, prefixCls + '-with-footer', !!footerDom)); var filteredDataSource = []; var totalDataSource = []; var showItems = dataSource.map(function (item) { var _renderItem = _this3.renderItem(item), renderedText = _renderItem.renderedText, renderedEl = _renderItem.renderedEl; if (filter && filter.trim() && !_this3.matchFilter(renderedText, item)) { return null; } // all show items totalDataSource.push(item); if (!item.disabled) { // response to checkAll items filteredDataSource.push(item); } var checked = checkedKeys.indexOf(item.key) >= 0; return React.createElement(Item, { key: item.key, item: item, lazy: lazy, renderedText: renderedText, renderedEl: renderedEl, checked: checked, prefixCls: prefixCls, onClick: _this3.handleSelect }); }); var unit = dataSource.length > 1 ? itemsUnit : itemUnit; var search = showSearch ? React.createElement( 'div', { className: prefixCls + '-body-search-wrapper' }, React.createElement(Search, { prefixCls: prefixCls + '-search', onChange: this.handleFilter, handleClear: this.handleClear, placeholder: searchPlaceholder, value: filter }) ) : null; var listBody = bodyDom || React.createElement( 'div', { className: showSearch ? prefixCls + '-body ' + prefixCls + '-body-with-search' : prefixCls + '-body' }, search, React.createElement( Animate, { component: 'ul', componentProps: { onScroll: onScroll }, className: prefixCls + '-content', transitionName: this.state.mounted ? prefixCls + '-content-item-highlight' : '', transitionLeave: false }, showItems ), React.createElement( 'div', { className: prefixCls + '-body-not-found' }, notFoundContent ) ); var listFooter = footerDom ? React.createElement( 'div', { className: prefixCls + '-footer' }, footerDom ) : null; var checkStatus = this.getCheckStatus(filteredDataSource); var checkedAll = checkStatus === 'all'; var checkAllCheckbox = React.createElement(Checkbox, { ref: 'checkbox', checked: checkedAll, indeterminate: checkStatus === 'part', onChange: function onChange() { return _this3.props.handleSelectAll(filteredDataSource, checkedAll); } }); return React.createElement( 'div', { className: listCls, style: style }, React.createElement( 'div', { className: prefixCls + '-header' }, checkAllCheckbox, React.createElement( 'span', { className: prefixCls + '-header-selected' }, React.createElement( 'span', null, (checkedKeys.length > 0 ? checkedKeys.length + '/' : '') + totalDataSource.length, ' ', unit ), React.createElement( 'span', { className: prefixCls + '-header-title' }, titleText ) ) ), listBody, listFooter ); } }]); return TransferList; }(React.Component); export default TransferList; TransferList.defaultProps = { dataSource: [], titleText: '', showSearch: false, render: noop, lazy: {} };
client/routes.js
AlexFrazer/site
import React from 'react'; import {Route, IndexRoute} from 'react-router'; import App from './containers/App'; import Home from './containers/HomePage'; import Users from './containers/Users'; import AddUser from './containers/AddUser'; import NotFound from './containers/NotFound'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/users" component={Users} /> <Route path="/create/user" component={AddUser} /> <Route path="*" component={NotFound} /> </Route> )
src/routes/notFound/NotFound.js
kinshuk-jain/TB-Dfront
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NotFound.css'; class NotFound extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>Sorry, the page you were trying to view does not exist.</p> </div> </div> ); } } export default withStyles(s)(NotFound);
pages/logout.js
1uphealth/1upwebapp
import React from 'react'; import Header from '../components/Header.js'; export default class Logout extends React.Component { static async getInitialProps({ req }) { const user = req ? req.user : null; return { user }; } componentDidMount() { if (this.props.user) { try { window.localStorage.setItem('user', this.props.user); } catch (err) {} } else if (typeof this.props.user !== 'undefined') { window.localStorage.removeItem('user'); } } render() { return ( <div> <Header /> <h1>Logged out!</h1> </div> ); } }
docs/index.js
rsuite/rsuite-tag
// 解决 IE 11 兼容性问题 import 'babel-polyfill'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Markdown } from 'react-markdown-reader'; import CodeView from 'react-code-view'; import { PageContainer } from 'rsuite-docs'; import './less/index.less'; import Tag, { TagGroup } from '../src'; import randomText from './util/randomText'; const tags = (() => { const common = Array.from(new Array(5)).map(() => `标签${randomText()}`); const custom = [ { text: `标签${randomText()}`, color: Tag.Color.PRIMARY, }, { text: `标签${randomText()}`, color: Tag.Color.SUCCESS, closable: true } ]; return [...custom, ...new Set(common)]; })(); class App extends Component { render() { return ( <PageContainer activeKey="Autocomplete" githubURL="https://github.com/rsuite/rsuite-autocomplete" > <Markdown>{require('../README.md')}</Markdown> <CodeView dependencies={{ React, Tag, randomText }} > {require('./md/basic.md')} </CodeView> <CodeView dependencies={{ React, Tag, TagGroup, randomText, tags }} > {require('./md/tagGroup.md')} </CodeView> <CodeView dependencies={{ React, Tag, TagGroup, randomText, tags }} babelTransformOptions={{ presets: [ 'es2015', 'react', 'stage-1' ] }} > {require('./md/tagGroupCustomized.md')} </CodeView> <Markdown>{require('./md/tagProps.md')}</Markdown> <Markdown>{require('./md/tagGroupProps.md')}</Markdown> </PageContainer> ); } } ReactDOM.render(<App />, document.getElementById('app') );
app/components/side_bar.js
uglymugs/JustNUM
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import { white } from 'material-ui/styles/colors'; import AssignmentLate from 'material-ui/svg-icons/action/assignment-late'; import Work from 'material-ui/svg-icons/action/work'; import NoteAdd from 'material-ui/svg-icons/action/note-add'; import Divider from 'material-ui/Divider'; import { Link } from 'react-router'; const style = { paper: { position: 'fixed', top: 0, left: 0, zIndex: 100, height: '100%', width: '224px', backgroundColor: '#5E7B8D', }, rightIcon: { textAlign: 'center', lineHeight: '24px', }, header: { display: 'flex', marginLeft: '10px', marginBottom: '5px', }, headerImg: { marginTop: '5px', width: '54px', height: '54px', }, headerText: { color: 'white', marginLeft: '8px', fontSize: '1.6em', }, }; const menuItemStyles = { color: 'white', }; const SideBar = () => <Paper style={style.paper}> <div style={style.header}> <img src="logo_sml.png" role="presentation" style={style.headerImg} /> <h1 style={style.headerText}>JustNUM</h1> </div> <Menu> <MenuItem primaryText="Tasks" style={menuItemStyles} leftIcon={<AssignmentLate color={white} />} containerElement={<Link to="/authenticated/tasks" />} /> <MenuItem primaryText="Cases" style={menuItemStyles} leftIcon={<Work color={white} />} containerElement={<Link to="/authenticated/cases" />} /> <Divider /> <MenuItem primaryText="Add Case" style={menuItemStyles} leftIcon={<NoteAdd color={white} />} containerElement={<Link to="/authenticated/cases/new" />} /> <Divider /> </Menu> </Paper>; export default SideBar;
src/pages/i-need-your-help.js
theanxy/wojtekzajac.com
import React from 'react'; import Helmet from 'react-helmet'; import Link from 'gatsby-link'; import styled from 'styled-components'; import Kenya from '../img/swahilibox/swahilibox.jpg'; const SwahiliboxPage = styled.div` line-height: 1.8; @media (min-width: 650px) { margin: 0 2.5em; } @media (min-width: 850px) { margin: 0 5em; p { margin-right: 20%; } } .caption { display: block; margin: -35px 10px 20px; text-align: right; color: rgba(0, 0, 0, 0.4); } p, ul { font-size: 14px; strong { font-weight: 600; } } li { margin-bottom: 0.2em; } .intro { font-size: 18px; margin-right: 0; } `; class Swahilibox extends React.Component { render() { return ( <SwahiliboxPage> <Helmet title="I need your help — Wojtek Zając" meta={[ { name: 'description', content: 'A perfect opportunity to support a thriving technical community in Mombasa.' } ]} /> <h1>I need your help! (Apologies for the clickbait 😉)</h1> <img src={Kenya} alt="Wojtek in Kenya" /> <small className="caption">Last week, assisting students in Mombasa</small> <p className="intro">Hello friend,</p> <p className="intro"> It's Wednesday, September 11th. I'm reaching out to you personally as I consider you someone who has inspired me in the past or just someone I genuinely look up to. </p> <p> <strong> I’m currently in Mombasa, Kenya during the 4th and final week of volunteering at a local NGO, SwahiliBox. </strong>{' '} For the past month, along with 2 colleagues of mine, we've been running various technical workshops. </p> <p> <strong>Yesterday</strong>, I've announced that I can run one more workshop this week, asking about the topic they would like me to cover. </p> <p> To my excitement, they've mentioned that{' '} <strong>they'd love to cover entrepreneurship and soft skills</strong>. I couldn't be happier about that! However, I then realized that after 3 weeks spent with them, distributing this process could both produce better results in terms of diversifying ideas, but also have a bigger impact that should hopefully push them to act more boldly :) </p> <h2>The idea</h2> <p style={{ fontSize: 16 }}> <strong> I'd like to create a compilation of short videos encouraging Swahilibox members to take action while keeping focused on their goals and thinking big. </strong> </p> <p> Ideally, a video should include at least one tip connected to:{' '} <strong> community leadership, networking, being searchable, understanding how to self-direct their growth, improving soft skills, validating business ideas, not being afraid to fail, etc. </strong>{' '} (Anything that would boost their careers other than technical skills, really.) </p> <h2>Rules</h2> <ul> <li>start with "hello swahilibox!"</li> <li>please don't mention me at all</li> <li> feel free to refer to your past experiences (explain how TAKING ACTION resulted in a very tangible and positive outcome) </li> <li>as for the duration, anything between 5 seconds and 5 minutes works</li> <li>horizontal orientation is strongly preferred, but not required</li> <li>feel free to forward to your friends if they'd like to contribute as well!</li> </ul> <h2>Target group</h2> <p> SwahiliBox currently consists of about 15 talented developers, mostly between 18-26 years old. Some are good with IoT, others already published native mobile apps, but the biggest group is eager to keep getting better at web development. </p> <p> Below are some of the members who stand out from the crowd, I think by referencing them personally we could have a bigger impact. </p> <ul> <li> <strong>Maria</strong>: an extremely dedicated person working long hours </li> <li> <strong>Isaac Nyakoi (Python Dev Entrepreneur)</strong>: He has been very dedicated in how he keeps coming to the space and loves to help others. He has started doing workshops when asked around Python and has even been teaching python in a bootcamp style learning environment. He also has his own startup which is in development stage. </li> <li> <strong>Abdallah</strong>: </li> <li> <strong>Dennis onkangi (IOT and Web Dev)</strong> has created Impact innovations to help communities including a very recent addition called TeleTap targeting Pregnant mothers during their pregnancy period. Since we all know miscarriages happen alot in africa due to long response times from medical personel. Thus they are making a small gadget that will allow for faster communication to health workers when a pregnant mother is in need of medical help. </li> <li> <strong>Abae Akili (Web and graphics Dev)</strong> Very dedicated to the community Runs workshops at SwahiliBox and does alot to help within SwahiliBox itself. He has a startup that looks at engaging people with emergency services closing the gap between the two entities. </li> <li> <strong>Muzammil Khan - (IOT Dev)</strong> A very energetic young highschool individual that has been instrumental in keeping the fire of IOT learning Alive at SwahiliBox he is doing his A-Levels and juggles full time education with being a vibrant community member. </li> <li>… TBD</li> </ul> <h2>Deadline</h2> <p> Our final session takes place on Friday, so{' '} <strong>I will need to receive all videos by Thursday, EOD</strong>. Afterwards, I'd like to screen it in front of the entire group. </p> <p> As soon as this project ends, you will get a link to the finished video. Every help counts and this is a chance for you to really influence the lives of these students. Any questions, just let me know! </p> <p className="intro"> Please send recorded videos until Thursday, EOD via email / dropbox / google drive / youtube to:{' '} <a href="mailto:[email protected]">[email protected]</a> </p> </SwahiliboxPage> ); } } export default Swahilibox;
src/components/SideBarList.js
jamescchu/jameschu-v5
import React from 'react' import Link from 'gatsby-link' import styled from 'styled-components' import { rhythm } from '../utils/typography' import { media } from '../utils/media' import PropTypes from 'prop-types' import StyledLink from './Link' const Content = styled.section`width: 100%;` const SideContainer = styled.ul` list-style: none; margin: 0; position: fixed; ${media.desktop` display: none; `}; ${media.giant` display: block; `}; ` const SideItem = styled.li`margin: 0;` const SideHeader = styled.span` font-size: ${rhythm(1 / 2)}; text-transform: uppercase; color: rgba(0, 0, 0, 0.5); ` const SideLink = StyledLink.withComponent(`a`) const SideBar = ({ sections }) => <SideContainer> <SideHeader>Contents</SideHeader> {sections && sections.split(', ').map((section, array) => <SideItem> <SideLink href={`#${section}`}> {section.replace(/-/g, ' ')} </SideLink> </SideItem> )} </SideContainer> SideBar.propTypes = { sections: PropTypes.string, } export default SideBar
src/components/MonsterManualItem.js
kristyjy/battleplan
import React from 'react'; import { ListGroupItem, Collapse, Button} from 'reactstrap'; import NPCStatBlock from './NPCStatBlock'; import classNames from 'classnames'; class MonsterManualItem extends React.Component { constructor(props, context) { super(props, context); this.toggle = this.toggle.bind(this); this.state = { collapse: false }; this.addToInitiative = this.addToInitiative.bind(this); } toggle() { this.setState({ collapse: !this.state.collapse }); } addToInitiative(item) { this.props.actions.addCombatant({ ...item, 'initiative': 0, 'isKO': false, 'isDead': false }); this.props.actions.sortCombatants(); } render() { const {item} = this.props; const listItemClasses = classNames({ 'monster-manual-list__item': true, 'monster-manual-list__item--open': this.state.collapse, 'justify-content-between': true }); return ( <div> <ListGroupItem className={listItemClasses} > <Button size="sm" onClick={() => { this.toggle(); }}>Details</Button> {item.name} <Button size="sm" onClick={() => { this.addToInitiative(item); }}>+</Button> </ListGroupItem> <Collapse isOpen={this.state.collapse}> <NPCStatBlock item={item} /> </Collapse> </div> ); } } MonsterManualItem.propTypes = { item : React.PropTypes.object.isRequired, actions : React.PropTypes.object.isRequired }; export default MonsterManualItem;
src/client.js
kayluhb/tbmaga
/** * THIS IS THE ENTRY POINT FOR THE CLIENT. */ import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; // import useScroll from 'scroll-behavior/lib/useStandardScroll'; import withScroll from 'scroll-behavior'; import { browserHistory as _browserHistory, Router, RouterContext } from 'react-router'; import { Provider } from 'react-redux'; import { syncHistoryWithStore } from 'react-router-redux'; import createStore from './redux/create'; import routes from './routes'; import { menuClose, placeCloseMedia } from './redux/modules/actions'; const browserHistory = withScroll(_browserHistory); const content = document.getElementById('content'); const store = createStore(browserHistory, window.initialState); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); const inProduction = process.env.NODE_ENV === 'production'; const component = ( <Router history={history} render={(props) => <RouterContext {...props} /> } > {routes()} </Router> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, content ); if (!inProduction) { if (!content || !content.firstChild || !content.firstChild.attributes || !content.firstChild.attributes['data-react-checksum']) { console.error( `Server-side React render was discarded. Make sure that your ` `initial render does not contain any client-side code.` ); } } else { /* eslint-disable */ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o), m=s.getElementsByTagName(o)[0]; a.async=1; a.src=g; m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-592045-7', 'auto'); ga('send', 'pageview'); /* eslint-enable */ } function onHistoryChange() { const state = store.getState(); if (state.menu.open) { store.dispatch(menuClose()); } if (state.place.mediaOpen) { store.dispatch(placeCloseMedia()); } if (inProduction) { window.ga('send', 'pageview'); } } history.listen(onHistoryChange); if (__DEVTOOLS__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, content ); }
client/component/schema/filter/types/member.js
johngodley/search-regex
/** * External dependencies */ import React from 'react'; import { translate as __ } from 'i18n-calypso'; import { useSelector, useDispatch } from 'react-redux'; /** * Internal dependencies */ import Logic from '../logic'; import { DropdownText, MultiOptionDropdown } from 'wp-plugin-components'; import SearchFlags from 'component/search-flags'; import { setLabel } from 'state/search/action'; import { getLabel } from 'state/search/selector'; function setValues( values, changed, all ) { if ( changed === '' ) { return values.indexOf( '' ) === -1 ? [] : all; } return values.filter( ( item ) => item !== '' ); } function getValues( values, allLength ) { if ( values.length === allLength ) { return [ '' ].concat( values ); } return values; } function getOptions( options ) { return [ { value: '', label: __( 'All' ), }, ].concat( options ); } function FilterMember( props ) { const { disabled, item, onChange, schema, fetchData } = props; const { logic = 'include', values = [], flags = [ 'case' ] } = item; const remote = schema.options === 'api' ? fetchData : false; const { labels } = useSelector( ( state ) => state.search ); const dispatch = useDispatch(); const logicComponent = ( <Logic type="member" value={ logic } disabled={ disabled } onChange={ ( value ) => onChange( { logic: value, values: [] } ) } /> ); if ( logic === 'contains' || logic === 'notcontains' ) { return ( <> { logicComponent } <DropdownText value={ values.length === 0 ? '' : values[ 0 ] } disabled={ disabled } onChange={ ( newValue ) => onChange( { values: [ newValue ] } ) } /> <SearchFlags flags={ flags } disabled={ disabled } onChange={ ( value ) => onChange( { flags: value } ) } allowRegex={ false } allowMultiline={ false } /> </> ); } if ( remote ) { return ( <> { logicComponent } <DropdownText value={ values } disabled={ disabled } onChange={ ( newValue ) => onChange( { values: newValue } ) } fetchData={ remote } loadOnFocus={ schema.preload } maxChoices={ 20 } onlyChoices setLabel={ ( labelId, labelValue ) => dispatch( setLabel( schema.column + '_' + labelId, labelValue ) ) } getLabel={ ( labelId ) => getLabel( labels, schema.column + '_' + labelId ) } /> </> ); } return ( <> { logicComponent } { ! remote && ( <MultiOptionDropdown options={ getOptions( schema.options ) } selected={ getValues( values, schema.options.length ) } onApply={ ( newValue, changed ) => onChange( { values: setValues( newValue, changed, schema.options.map( ( item ) => item.value ) ), } ) } multiple={ schema.multiple ?? true } disabled={ disabled } hideTitle title={ schema.title } badges customBadge={ ( selected ) => ( selected.length >= schema.options.length ? [ '' ] : selected ) } /> ) } </> ); } export default FilterMember;
src/server.js
vincentbello/isomorphic-networker
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; import {ReduxRouter} from 'redux-router'; import createHistory from 'history/lib/createMemoryHistory'; import {reduxReactRouter, match} from 'redux-router/server'; import {Provider} from 'react-redux'; import qs from 'query-string'; import getRoutes from './routes'; import getStatusFromRoutes from './helpers/getStatusFromRoutes'; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: 'http://' + config.apiHost + ':' + config.apiPort, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(require('serve-static')(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const store = createStore(reduxReactRouter, getRoutes, createHistory, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (!routerState) { res.status(500); hydrateOnClient(); } else { // Workaround redux-router query string issue: // https://github.com/rackt/redux-router/issues/106 if (routerState.location.search && !routerState.location.query) { routerState.location.query = qs.parse(routerState.location.search); } store.getState().router.then(() => { const component = ( <Provider store={store} key="provider"> <ReduxRouter/> </Provider> ); const status = getStatusFromRoutes(routerState.routes); if (status) { res.status(status); } res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }).catch((err) => { console.error('DATA FETCHING ERROR:', pretty.render(err)); res.status(500); hydrateOnClient(); }); } })); }); if (config.port) { if (config.isProduction) { const io = new SocketIo(server); io.path('/api/ws'); } server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
app/containers/Mt2Mobile/index.js
Blacksage959/Michael.McCann
/* * * Mt2Mobile * */ import React from 'react'; import Helmet from 'react-helmet'; export default class Mt2Mobile extends React.PureComponent { render() { return ( <div> <Helmet title="Mt2Mobile" meta={[ { name: 'description', content: 'Description of Mt2Mobile' }]}/> //Remove this line and you can start writing your code here. </div> ); } }
src/FormsyRadioGroup/FormsyRadioGroup.spec.js
maccuaa/formsy-mui
import 'jsdom-global/register'; import React from 'react'; import PropTypes from 'prop-types'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import {Form} from 'formsy-react-2'; import Enzyme, { mount } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import test from 'tape'; import Sinon from 'sinon'; import RadioButtonGroup from 'material-ui/RadioButton/RadioButtonGroup'; import FormsyRadio from '../FormsyRadio'; import FormsyRadioGroup from './FormsyRadioGroup'; Enzyme.configure({ adapter: new Adapter() }); const muiTheme = getMuiTheme(); const mountWithContext = (node) => mount(node, { context: {muiTheme}, childContextTypes: {muiTheme: PropTypes.object.isRequired} }); test('FormsyRadioGroup renders a material-ui RadioButtonGroup', (assert) => { const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='test' /> </Form> ); assert.equals(wrapper.find(RadioButtonGroup).length, 1); assert.end(); }); test('FormsyRadioGroup sends value to Formsy Form', (assert) => { const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='test' valueSelected='foo'> <FormsyRadio value='foo' /> </FormsyRadioGroup> </Form> ); const expected = 'foo'; const formsyForm = wrapper.find(Form).instance(); const input = wrapper.find('input').instance(); // Make sure the Formsy Form component has the right value assert.equals(formsyForm.getCurrentValues().test, expected); // Make sure the DOM has the right value assert.true(input.checked); assert.end(); }); test('FormsyRadioGroup resetValue sets value back to original value', (assert) => { const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='test' valueSelected='foo'> <FormsyRadio value='foo' /> <FormsyRadio value='bar' /> </FormsyRadioGroup> </Form> ); const formsyRadioGroup = wrapper.find(FormsyRadioGroup).instance(); const fooInput = wrapper.find({value: 'foo'}).last(); const barInput = wrapper.find({value: 'bar'}).last(); assert.false(barInput.instance().checked); assert.true(fooInput.instance().checked); assert.equals(formsyRadioGroup.getValue(), 'foo'); barInput.instance().checked = true; barInput.simulate('change'); assert.equals(formsyRadioGroup.getValue(), 'bar'); assert.true(barInput.instance().checked); assert.false(fooInput.instance().checked); formsyRadioGroup.resetValue(); assert.equals(formsyRadioGroup.getValue(), 'foo'); assert.false(barInput.instance().checked); assert.true(fooInput.instance().checked); assert.end(); }); test('FormsyRadioGroup onChange prop is called', (assert) => { const onChangeSpy = Sinon.spy(); const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='test' onChange={onChangeSpy}> <FormsyRadio value='foo' /> </FormsyRadioGroup> </Form> ); wrapper.find({value: 'foo'}).last().simulate('change'); assert.true(onChangeSpy.calledOnce); assert.end(); }); test('FormsyRadioGroup falsey valueSelected values are correctly set', (assert) => { const zero = 0; const notTrue = false; const nill = null; const notdefined = undefined; const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='zero' valueSelected={zero}> <FormsyRadio value={zero} /> </FormsyRadioGroup> <FormsyRadioGroup name='notTrue' valueSelected={notTrue}> <FormsyRadio value={notTrue} /> </FormsyRadioGroup> <FormsyRadioGroup name='nill' valueSelected={nill}> <FormsyRadio value={nill} /> </FormsyRadioGroup> <FormsyRadioGroup name='notdefined' valueSelected={notdefined}> <FormsyRadio value={notdefined} /> </FormsyRadioGroup> </Form> ); const formsyForm = wrapper.find(Form).instance(); const formValues = formsyForm.getCurrentValues(); assert.equals(formValues.zero, zero); assert.equals(formValues.notTrue, notTrue); assert.equals(formValues.nill, nill); assert.equals(formValues.notdefined, notdefined); assert.end(); }); test('FormsyRadioGroup falsey defaultSelected values are correctly set', (assert) => { const zero = 0; const notTrue = false; const nill = null; const notdefined = undefined; const wrapper = mountWithContext( <Form> <FormsyRadioGroup name='zero' defaultSelected={zero}> <FormsyRadio value={zero} /> </FormsyRadioGroup> <FormsyRadioGroup name='notTrue' defaultSelected={notTrue}> <FormsyRadio value={notTrue} /> </FormsyRadioGroup> <FormsyRadioGroup name='nill' defaultSelected={nill}> <FormsyRadio value={nill} /> </FormsyRadioGroup> <FormsyRadioGroup name='notdefined' defaultSelected={notdefined}> <FormsyRadio value={notdefined} /> </FormsyRadioGroup> </Form> ); const formsyForm = wrapper.find(Form).instance(); const formValues = formsyForm.getCurrentValues(); assert.equals(formValues.zero, zero); assert.equals(formValues.notTrue, notTrue); assert.equals(formValues.nill, nill); assert.equals(formValues.notdefined, notdefined); assert.end(); }); test('FormsyRadioGroup updates value as a controlled component', (assert) => { class MyComponent extends React.PureComponent { constructor (props) { super(props); this.state = { value: 'foo' }; } changeValue () { this.setState({value: 'bar'}); } render () { return ( <Form> <FormsyRadioGroup name='test' valueSelected={this.state.value}> <FormsyRadio value='foo' /> <FormsyRadio value='bar' /> </FormsyRadioGroup> </Form> ); } } const wrapper = mountWithContext(<MyComponent />); const formsyForm = wrapper.find(Form).instance(); const myComponent = wrapper.find(MyComponent).instance(); const formsyRadioGroup = wrapper.find(FormsyRadioGroup).instance(); const radioButtonGroup = wrapper.find(RadioButtonGroup).instance(); const fooInput = wrapper.find({value: 'foo'}).last(); const barInput = wrapper.find({value: 'bar'}).last(); assert.equals(formsyForm.getCurrentValues().test, 'foo'); assert.false(barInput.instance().checked); assert.true(fooInput.instance().checked); assert.equals(formsyRadioGroup.getValue(), 'foo'); assert.equals(radioButtonGroup.getSelectedValue(), 'foo'); myComponent.changeValue(); assert.equals(formsyForm.getCurrentValues().test, 'bar'); assert.true(barInput.instance().checked); assert.false(fooInput.instance().checked); assert.equals(formsyRadioGroup.getValue(), 'bar'); assert.equals(radioButtonGroup.getSelectedValue(), 'bar'); assert.end(); });
actor-apps/app-web/src/app/components/modals/MyProfile.react.js
gaolichuang/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import { Container } from 'flux/utils'; import Modal from 'react-modal'; import ActorClient from 'utils/ActorClient'; import { KeyCodes } from 'constants/ActorAppConstants'; import MyProfileActions from 'actions/MyProfileActionCreators'; import CropAvatarActionCreators from 'actions/CropAvatarActionCreators'; import MyProfileStore from 'stores/MyProfileStore'; import CropAvatarStore from 'stores/CropAvatarStore'; import AvatarItem from 'components/common/AvatarItem.react'; import CropAvatarModal from './CropAvatar.react.js'; import { Styles, TextField } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); class MyProfile extends Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } static getStores = () => [MyProfileStore, CropAvatarStore]; static calculateState() { return { profile: MyProfileStore.getProfile(), name: MyProfileStore.getName(), nick: MyProfileStore.getNick(), about: MyProfileStore.getAbout(), isOpen: MyProfileStore.isModalOpen(), isCropModalOpen: CropAvatarStore.isOpen() }; } componentWillMount() { ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7', disabledTextColor: 'rgba(0,0,0,.4)' } }); } componentWillUpdate(nextProps, nextState) { if ((nextState.isOpen && !this.state.isOpen) || (this.state.isOpen && !nextState.isCropModalOpen)) { document.addEventListener('keydown', this.onKeyDown, false); } else if ((!nextState.isOpen && this.state.isOpen) || (this.state.isOpen && nextState.isCropModalOpen)) { document.removeEventListener('keydown', this.onKeyDown, false); } } onClose = () => MyProfileActions.hide(); onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onNameChange = event => this.setState({name: event.target.value}); onNicknameChange = event => this.setState({nick: event.target.value}); onAboutChange = event => this.setState({about: event.target.value}); onSave = () => { const { nick, name, about } = this.state; MyProfileActions.saveName(name); MyProfileActions.saveNickname(nick); MyProfileActions.editMyAbout(about); this.onClose(); }; onProfilePictureInputChange = () => { const imageInput = React.findDOMNode(this.refs.imageInput); const imageForm = React.findDOMNode(this.refs.imageForm); const file = imageInput.files[0]; let reader = new FileReader(); reader.onload = (event) => { CropAvatarActionCreators.show(event.target.result); imageForm.reset(); }; reader.readAsDataURL(file); }; onChangeAvatarClick = () => { const imageInput = React.findDOMNode(this.refs.imageInput); imageInput.click() }; onProfilePictureRemove = () => MyProfileActions.removeMyAvatar(); changeMyAvatar = (croppedImage) => MyProfileActions.changeMyAvatar(croppedImage); render() { const { isOpen, isCropModalOpen, profile, nick, name, about } = this.state; const cropAvatar = isCropModalOpen ? <CropAvatarModal onCropFinish={this.changeMyAvatar}/> : null; if (profile !== null && isOpen) { return ( <Modal className="modal-new modal-new--profile" closeTimeoutMS={150} isOpen={isOpen} style={{width: 440}}> <header className="modal-new__header"> <a className="modal-new__header__icon material-icons">person</a> <h4 className="modal-new__header__title">Profile</h4> <div className="pull-right"> <button className="button button--lightblue" onClick={this.onSave}>Done</button> </div> </header> <div className="modal-new__body row"> <div className="col-xs"> <div className="name"> <TextField className="login__form__input" floatingLabelText="Full name" fullWidth onChange={this.onNameChange} type="text" value={name}/> </div> <div className="nick"> <TextField className="login__form__input" floatingLabelText="Nickname" fullWidth onChange={this.onNicknameChange} type="text" value={nick}/> </div> <div className="phone"> <TextField className="login__form__input" disabled floatingLabelText="Phone number" fullWidth type="tel" value={(profile.phones[0] || {}).number}/> </div> <div className="about"> <label htmlFor="about">About</label> <textarea className="textarea" id="about" onChange={this.onAboutChange} placeholder="Few words about you" value={about}/> </div> </div> <div className="profile-picture text-center"> <div className="profile-picture__changer"> <AvatarItem image={profile.bigAvatar} placeholder={profile.placeholder} size="big" title={profile.name}/> <a onClick={this.onChangeAvatarClick}> <span>Change</span> <span>avatar</span> </a> </div> <div className="profile-picture__controls"> <a onClick={this.onProfilePictureRemove}>Remove</a> </div> <form className="hide" ref="imageForm"> <input onChange={this.onProfilePictureInputChange} ref="imageInput" type="file"/> </form> </div> </div> {cropAvatar} </Modal> ); } else { return null; } } } export default Container.create(MyProfile, {pure: false});
src/svg-icons/action/swap-vertical-circle.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVerticalCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM6.5 9L10 5.5 13.5 9H11v4H9V9H6.5zm11 6L14 18.5 10.5 15H13v-4h2v4h2.5z"/> </SvgIcon> ); ActionSwapVerticalCircle = pure(ActionSwapVerticalCircle); ActionSwapVerticalCircle.displayName = 'ActionSwapVerticalCircle'; ActionSwapVerticalCircle.muiName = 'SvgIcon'; export default ActionSwapVerticalCircle;
client/modules/User/pages/UserBasePage.js
vwtan/FinancialTracker
import React from 'react'; import { Link } from 'react-router'; import styles from '../styles/User.scss'; import Sidebar from '../components/Sidebar'; /* eslint react/prop-types: 0 */ export function UserBasePage(props) { return ( <div className={styles.bg}> <Sidebar /> { props.children } </div> ); } export default UserBasePage;
src-example/components/molecules/Blockquote/index.js
SIB-Colombia/biodiversity_catalogue_v2_frontend
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import { font, palette } from 'styled-theme' const StyledBlockquote = styled.blockquote` position: relative; font-family: ${font('quote')}; font-style: italic; font-size: 1.2rem; line-height: 2rem; box-sizing: border-box; color: ${palette('grayscale', 1)}; border-left: 5px solid ${palette('grayscale', 2, true)}; margin: 1rem 0; padding: 0.5rem 0 0.5rem 1.5rem; ` const Cite = styled.cite` display: block; font-family: ${font('primary')}; font-weight: 300; font-style: normal; margin-top: 0.4rem; ` const Blockquote = ({ cite, children, ...props }) => { return ( <StyledBlockquote {...props}> <div>{children}</div> {cite && <Cite>{cite}</Cite>} </StyledBlockquote> ) } Blockquote.propTypes = { cite: PropTypes.string, children: PropTypes.node, reverse: PropTypes.bool, } export default Blockquote
app/components/ToolboxComponent.js
ARMataTeam/ARMata
// @flow import React, { Component } from 'react'; import { Image, Icon } from 'semantic-ui-react'; import { DragSource } from 'react-dnd'; import ImageGenerator from '../resources/imageGenerator'; import styles from './ToolboxComponent.css'; // eslint-disable-line flowtype-errors/show-errors const componentSource = { beginDrag(props) { return { name: props.name, }; }, endDrag(props, monitor) { const dropResult = monitor.getDropResult(); if (dropResult) { try { props.addResource(props.resourceType); } catch (ex) { props.error(ex.toString()); } } }, }; class ToolboxComponent extends Component { props: { addResource: (resourceType: string) => void, // eslint-disable-line react/no-unused-prop-types error: (errorMessage: string) => void, // eslint-disable-line react/no-unused-prop-types resourceType: string } render() { return this.props.connectDragSource(<div><Icon circular className={styles.toolboxIcon} size="big"><Image src={ImageGenerator.findImage(this.props.resourceType)} size="mini" centered /></Icon></div>); // eslint-disable-line react/prop-types } } export default DragSource('Component', componentSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }))(ToolboxComponent);
src/Divider/Divider.js
pradel/material-ui
import React from 'react'; const propTypes = { /** * The css class name of the root element. */ className: React.PropTypes.string, /** * If true, the `Divider` will be indented `72px`. */ inset: React.PropTypes.bool, /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, }; const defaultProps = { inset: false, }; const contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; const Divider = (props, context) => { const { inset, style, ...other, } = props; const {muiTheme} = context; const {prepareStyles} = muiTheme; const styles = { root: { margin: 0, marginTop: -1, marginLeft: inset ? 72 : 0, height: 1, border: 'none', backgroundColor: muiTheme.baseTheme.palette.borderColor, }, }; return ( <hr {...other} style={prepareStyles(Object.assign({}, styles.root, style))} /> ); }; Divider.muiName = 'Divider'; Divider.propTypes = propTypes; Divider.defaultProps = defaultProps; Divider.contextTypes = contextTypes; export default Divider;
src/svg-icons/device/signal-wifi-1-bar-lock.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi1BarLock = (props) => ( <SvgIcon {...props}> <path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/> </SvgIcon> ); DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock); DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock'; DeviceSignalWifi1BarLock.muiName = 'SvgIcon'; export default DeviceSignalWifi1BarLock;
pages/index.js
fmarcos83/mdocs
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Home Page</h1> <p>Coming soon.</p> </div> ); } }
project-the-best/src/index.js
renhongl/Summary
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom'; import { Home } from './component/home'; import { Login } from './component/login'; import 'antd/dist/antd.less'; import './share/style/global.less'; import './share/mr/mr.css'; let loggedIn = window.localStorage.getItem('loggedIn'); class App extends Component{ constructor(props) { super(props); this.state = { loggedIn: true } } login = () => { this.setState({ loggedIn: true }) } logout = () => { this.setState({ loggedIn: false }) } render() { return ( <Router> <div className='home'> <Route exact path='/' component={Home}></Route> {/* <Route exact path="/" render={() => ( this.state.loggedIn ? ( <Redirect to="/home"/> ) : ( <Login login={this.login}/> ) )}/> */} </div> </Router> ) } } ReactDOM.render( <App />, document.getElementById('root') )
client/src/templates/Challenges/components/Challenge-Title.js
pahosler/freecodecamp
import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { children: PropTypes.string, isCompleted: PropTypes.bool }; function ChallengeTitle({ children, isCompleted }) { let icon = null; if (isCompleted) { icon = ( // TODO Use SVG here <i className='ion-checkmark-circled text-primary' title='Completed' /> ); } return ( <h2 className='text-center challenge-title'> {children || 'Happy Coding!'} {icon} </h2> ); } ChallengeTitle.displayName = 'ChallengeTitle'; ChallengeTitle.propTypes = propTypes; export default ChallengeTitle;
src/Parser/Core/CombatLogParser.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ChangelogTab from 'Main/ChangelogTab'; import ChangelogTabTitle from 'Main/ChangelogTabTitle'; import TimelineTab from 'Main/Timeline/TimelineTab'; import { formatNumber, formatPercentage, formatThousands, formatDuration } from 'common/format'; import { findByBossId } from 'Raids'; import ApplyBuffNormalizer from './Normalizers/ApplyBuff'; import CancelledCastsNormalizer from './Normalizers/CancelledCasts'; import Status from './Modules/Status'; import HealingDone from './Modules/HealingDone'; import DamageDone from './Modules/DamageDone'; import DamageTaken from './Modules/DamageTaken'; import DeathTracker from './Modules/DeathTracker'; import Combatants from './Modules/Combatants'; import AbilityTracker from './Modules/AbilityTracker'; import Haste from './Modules/Haste'; import StatTracker from './Modules/StatTracker'; import AlwaysBeCasting from './Modules/AlwaysBeCasting'; import Abilities from './Modules/Abilities'; import CastEfficiency from './Modules/CastEfficiency'; import SpellUsable from './Modules/SpellUsable'; import SpellHistory from './Modules/SpellHistory'; import GlobalCooldown from './Modules/GlobalCooldown'; import Enemies from './Modules/Enemies'; import EnemyInstances from './Modules/EnemyInstances'; import Pets from './Modules/Pets'; import HealEventTracker from './Modules/HealEventTracker'; import ManaValues from './Modules/ManaValues'; import SpellManaCost from './Modules/SpellManaCost'; import Channeling from './Modules/Channeling'; import DistanceMoved from './Modules/Others/DistanceMoved'; import CharacterPanel from './Modules/Features/CharacterPanel'; import StatsDisplay from './Modules/Features/StatsDisplay'; import TalentsDisplay from './Modules/Features/TalentsDisplay'; import Checklist from './Modules/Features/Checklist'; import CritEffectBonus from './Modules/Helpers/CritEffectBonus'; import PrePotion from './Modules/Items/PrePotion'; import LegendaryUpgradeChecker from './Modules/Items/LegendaryUpgradeChecker'; import LegendaryCountChecker from './Modules/Items/LegendaryCountChecker'; import EnchantChecker from './Modules/Items/EnchantChecker'; // Legendaries import PrydazXavaricsMagnumOpus from './Modules/Items/Legion/Legendaries/PrydazXavaricsMagnumOpus'; import VelensFutureSight from './Modules/Items/Legion/Legendaries/VelensFutureSight'; import SephuzsSecret from './Modules/Items/Legion/Legendaries/SephuzsSecret'; import KiljaedensBurningWish from './Modules/Items/Legion/Legendaries/KiljaedensBurningWish'; import ArchimondesHatredReborn from './Modules/Items/Legion/Legendaries/ArchimondesHatredReborn'; import CinidariaTheSymbiote from './Modules/Items/Legion/Legendaries/CinidariaTheSymbiote'; import InsigniaOfTheGrandArmy from './Modules/Items/Legion/Legendaries/InsigniaOfTheGrandArmy'; import AmanthulsVision from './Modules/Items/Legion/Legendaries/AmanthulsVision'; // Dungeons/crafted import DrapeOfShame from './Modules/Items/Legion/DrapeOfShame'; import DarkmoonDeckPromises from './Modules/Items/Legion/DarkmoonDeckPromises'; import DarkmoonDeckImmortality from './Modules/Items/Legion/DarkmoonDeckImmortality'; import AmalgamsSeventhSpine from './Modules/Items/Legion/AmalgamsSeventhSpine'; import GnawedThumbRing from './Modules/Items/Legion/GnawedThumbRing'; import EyeOfCommand from './Modules/Items/Legion/EyeOfCommand'; // The Nighthold (T19) import ErraticMetronome from './Modules/Items/Legion/TheNighthold/ErraticMetronome'; // Tomb of Sargeras (T20) import ArchiveOfFaith from './Modules/Items/Legion/TombOfSargeras/ArchiveOfFaith'; import TarnishedSentinelMedallion from './Modules/Items/Legion/TombOfSargeras/TarnishedSentinelMedallion'; import SeaStarOfTheDepthmother from './Modules/Items/Legion/TombOfSargeras/SeaStarOfTheDepthmother'; import DeceiversGrandDesign from './Modules/Items/Legion/TombOfSargeras/DeceiversGrandDesign'; import BarbaricMindslaver from './Modules/Items/Legion/TombOfSargeras/BarbaricMindslaver'; import CharmOfTheRisingTide from './Modules/Items/Legion/TombOfSargeras/CharmOfTheRisingTide'; import EngineOfEradication from './Modules/Items/Legion/TombOfSargeras/EngineOfEradication'; import InfernalCinders from './Modules/Items/Legion/TombOfSargeras/InfernalCinders'; import SpecterOfBetrayal from './Modules/Items/Legion/TombOfSargeras/SpecterOfBetrayal'; import SpectralThurible from './Modules/Items/Legion/TombOfSargeras/SpectralThurible'; import TerrorFromBelow from './Modules/Items/Legion/TombOfSargeras/TerrorFromBelow'; import TomeOfUnravelingSanity from './Modules/Items/Legion/TombOfSargeras/TomeOfUnravelingSanity'; import UmbralMoonglaives from './Modules/Items/Legion/TombOfSargeras/UmbralMoonglaives'; import VialOfCeaselessToxins from './Modules/Items/Legion/TombOfSargeras/VialOfCeaselessToxins'; // Antorus, the Burning Throne (T21) // Healing import TarratusKeystone from './Modules/Items/Legion/AntorusTheBurningThrone/TarratusKeystone'; import HighFathersMachination from './Modules/Items/Legion/AntorusTheBurningThrone/HighfathersMachination'; import EonarsCompassion from './Modules/Items/Legion/AntorusTheBurningThrone/EonarsCompassion'; import GarothiFeedbackConduit from './Modules/Items/Legion/AntorusTheBurningThrone/GarothiFeedbackConduit'; import CarafeOfSearingLight from './Modules/Items/Legion/AntorusTheBurningThrone/CarafeOfSearingLight'; import IshkarsFelshieldEmitter from './Modules/Items/Legion/AntorusTheBurningThrone/IshkarsFelshieldEmitter'; // DPS import SeepingScourgewing from './Modules/Items/Legion/AntorusTheBurningThrone/SeepingScourgewing'; import GorshalachsLegacy from './Modules/Items/Legion/AntorusTheBurningThrone/GorshalachsLegacy'; import GolgannethsVitality from './Modules/Items/Legion/AntorusTheBurningThrone/GolgannethsVitality'; import ForgefiendsFabricator from './Modules/Items/Legion/AntorusTheBurningThrone/ForgefiendsFabricator'; import KhazgorothsCourage from './Modules/Items/Legion/AntorusTheBurningThrone/KhazgorothsCourage'; import TerminusSignalingBeacon from './Modules/Items/Legion/AntorusTheBurningThrone/TerminusSignalingBeacon'; import PrototypePersonnelDecimator from './Modules/Items/Legion/AntorusTheBurningThrone/PrototypePersonnelDecimator'; import SheathOfAsara from './Modules/Items/Legion/AntorusTheBurningThrone/SheathOfAsara'; import NorgannonsProwess from './Modules/Items/Legion/AntorusTheBurningThrone/NorgannonsProwess'; import AcridCatalystInjector from './Modules/Items/Legion/AntorusTheBurningThrone/AcridCatalystInjector'; import ShadowSingedFang from './Modules/Items/Legion/AntorusTheBurningThrone/ShadowSingedFang'; // Tanking import AggramarsConviction from './Modules/Items/Legion/AntorusTheBurningThrone/AggramarsConviction'; // Shared Buffs import Concordance from './Modules/Spells/Concordance'; import VantusRune from './Modules/Spells/VantusRune'; // Netherlight Crucible Traits import DarkSorrows from './Modules/NetherlightCrucibleTraits/DarkSorrows'; import TormentTheWeak from './Modules/NetherlightCrucibleTraits/TormentTheWeak'; import ChaoticDarkness from './Modules/NetherlightCrucibleTraits/ChaoticDarkness'; import Shadowbind from './Modules/NetherlightCrucibleTraits/Shadowbind'; import LightsEmbrace from './Modules/NetherlightCrucibleTraits/LightsEmbrace'; import InfusionOfLight from './Modules/NetherlightCrucibleTraits/InfusionOfLight'; import SecureInTheLight from './Modules/NetherlightCrucibleTraits/SecureInTheLight'; import Shocklight from './Modules/NetherlightCrucibleTraits/Shocklight'; import MurderousIntent from './Modules/NetherlightCrucibleTraits/MurderousIntent'; import MasterOfShadows from './Modules/NetherlightCrucibleTraits/MasterOfShadows'; import LightSpeed from './Modules/NetherlightCrucibleTraits/LightSpeed'; import RefractiveShell from './Modules/NetherlightCrucibleTraits/RefractiveShell'; import NLCTraits from './Modules/NetherlightCrucibleTraits/NLCTraits'; import ParseResults from './ParseResults'; import Analyzer from './Analyzer'; import EventsNormalizer from './EventsNormalizer'; // This prints to console anything that the DI has to do const debugDependencyInjection = false; // This sends every event that occurs to the console, including fabricated events (unlike the Events tab) const debugEvents = false; let _modulesDeprecatedWarningSent = false; class CombatLogParser { static abilitiesAffectedByHealingIncreases = []; static defaultModules = { // Normalizers applyBuffNormalizer: ApplyBuffNormalizer, cancelledCastsNormalizer: CancelledCastsNormalizer, // Analyzers status: Status, healingDone: HealingDone, damageDone: DamageDone, damageTaken: DamageTaken, deathTracker: DeathTracker, combatants: Combatants, enemies: Enemies, enemyInstances: EnemyInstances, pets: Pets, spellManaCost: SpellManaCost, channeling: Channeling, abilityTracker: AbilityTracker, healEventTracker: HealEventTracker, haste: Haste, statTracker: StatTracker, alwaysBeCasting: AlwaysBeCasting, abilities: Abilities, CastEfficiency: CastEfficiency, spellUsable: SpellUsable, spellHistory: SpellHistory, globalCooldown: GlobalCooldown, manaValues: ManaValues, vantusRune: VantusRune, distanceMoved: DistanceMoved, critEffectBonus: CritEffectBonus, characterPanel: CharacterPanel, statsDisplay: StatsDisplay, talentsDisplay: TalentsDisplay, checklist: Checklist, // Items: // Legendaries: prydazXavaricsMagnumOpus: PrydazXavaricsMagnumOpus, velensFutureSight: VelensFutureSight, sephuzsSecret: SephuzsSecret, kiljaedensBurningWish: KiljaedensBurningWish, archimondesHatredReborn: ArchimondesHatredReborn, cinidariaTheSymbiote: CinidariaTheSymbiote, insigniaOfTheGrandArmy: InsigniaOfTheGrandArmy, amanthulsVision: AmanthulsVision, // Epics: drapeOfShame: DrapeOfShame, amalgamsSeventhSpine: AmalgamsSeventhSpine, darkmoonDeckPromises: DarkmoonDeckPromises, darkmoonDeckImmortality: DarkmoonDeckImmortality, prePotion: PrePotion, legendaryUpgradeChecker: LegendaryUpgradeChecker, legendaryCountChecker: LegendaryCountChecker, enchantChecker: EnchantChecker, gnawedThumbRing: GnawedThumbRing, ishkarsFelshieldEmitter: IshkarsFelshieldEmitter, erraticMetronome: ErraticMetronome, eyeOfCommand: EyeOfCommand, // Tomb trinkets: archiveOfFaith: ArchiveOfFaith, barbaricMindslaver: BarbaricMindslaver, charmOfTheRisingTide: CharmOfTheRisingTide, seaStarOfTheDepthmother: SeaStarOfTheDepthmother, deceiversGrandDesign: DeceiversGrandDesign, vialCeaslessToxins: VialOfCeaselessToxins, specterOfBetrayal: SpecterOfBetrayal, engineOfEradication: EngineOfEradication, tarnishedSentinelMedallion: TarnishedSentinelMedallion, spectralThurible: SpectralThurible, terrorFromBelow: TerrorFromBelow, tomeOfUnravelingSanity: TomeOfUnravelingSanity, // T21 Healing Trinkets tarratusKeystone: TarratusKeystone, highfathersMachinations: HighFathersMachination, eonarsCompassion: EonarsCompassion, garothiFeedbackConduit: GarothiFeedbackConduit, carafeOfSearingLight: CarafeOfSearingLight, // T21 DPS Trinkets seepingScourgewing: SeepingScourgewing, gorshalachsLegacy: GorshalachsLegacy, golgannethsVitality: GolgannethsVitality, forgefiendsFabricator: ForgefiendsFabricator, khazgorothsCourage: KhazgorothsCourage, terminusSignalingBeacon: TerminusSignalingBeacon, prototypePersonnelDecimator: PrototypePersonnelDecimator, sheathOfAsara: SheathOfAsara, norgannonsProwess: NorgannonsProwess, acridCatalystInjector: AcridCatalystInjector, shadowSingedFang: ShadowSingedFang, // T21 Tanking Trinkets aggramarsConviction: AggramarsConviction, // Concordance of the Legionfall concordance: Concordance, // Netherlight Crucible Traits darkSorrows: DarkSorrows, tormentTheWeak: TormentTheWeak, chaoticDarkness: ChaoticDarkness, shadowbind: Shadowbind, lightsEmbrace: LightsEmbrace, infusionOfLight: InfusionOfLight, secureInTheLight: SecureInTheLight, shocklight: Shocklight, refractiveShell: RefractiveShell, murderousIntent: MurderousIntent, masterOfShadows: MasterOfShadows, lightSpeed: LightSpeed, nlcTraits: NLCTraits, infernalCinders: InfernalCinders, umbralMoonglaives: UmbralMoonglaives, }; // Override this with spec specific modules when extending static specModules = {}; report = null; player = null; playerPets = null; fight = null; _modules = {}; get modules() { if (!_modulesDeprecatedWarningSent) { console.error('Using `this.owner.modules` is deprecated. You should add the module you want to use as a dependency and use the property that\'s added to your module instead.'); _modulesDeprecatedWarningSent = true; } return this._modules; } get activeModules() { return Object.keys(this._modules) .map(key => this._modules[key]) .filter(module => module.active); } get playerId() { return this.player.id; } _timestamp = null; get currentTimestamp() { return this.finished ? this.fight.end_time : this._timestamp; } get fightDuration() { return this.currentTimestamp - this.fight.start_time; } get finished() { return this._modules.status.finished; } get playersById() { return this.report.friendlies.reduce((obj, player) => { obj[player.id] = player; return obj; }, {}); } constructor(report, player, playerPets, fight) { this.report = report; this.player = player; this.playerPets = playerPets; this.fight = fight; if (fight) { this._timestamp = fight.start_time; this.boss = findByBossId(fight.boss); } else if (process.env.NODE_ENV !== 'test') { throw new Error('fight argument was empty.'); } this.initializeModules({ ...this.constructor.defaultModules, ...this.constructor.specModules, }); } initializeModules(modules) { const failedModules = []; Object.keys(modules).forEach(desiredModuleName => { const moduleConfig = modules[desiredModuleName]; if (!moduleConfig) { return; } let moduleClass; let options; if (moduleConfig instanceof Array) { moduleClass = moduleConfig[0]; options = moduleConfig[1]; } else { moduleClass = moduleConfig; options = null; } const availableDependencies = {}; const missingDependencies = []; if (moduleClass.dependencies) { Object.keys(moduleClass.dependencies).forEach(desiredDependencyName => { const dependencyClass = moduleClass.dependencies[desiredDependencyName]; const dependencyModule = this.findModule(dependencyClass); if (dependencyModule) { availableDependencies[desiredDependencyName] = dependencyModule; } else { missingDependencies.push(dependencyClass); } }); } if (missingDependencies.length === 0) { if (debugDependencyInjection) { if (Object.keys(availableDependencies).length === 0) { console.log('Loading', moduleClass.name); } else { console.log('Loading', moduleClass.name, 'with dependencies:', Object.keys(availableDependencies)); } } // eslint-disable-next-line new-cap const module = new moduleClass(this, availableDependencies, Object.keys(this._modules).length); // We can't set the options via the constructor since a parent constructor can't override the values of a child's class properties. // See https://github.com/Microsoft/TypeScript/issues/6110 for more info if (options) { Object.keys(options).forEach(key => module[key] = options[key]); } this._modules[desiredModuleName] = module; } else { debugDependencyInjection && console.warn(moduleClass.name, 'could not be loaded, missing dependencies:', missingDependencies.map(d => d.name)); failedModules.push(desiredModuleName); } }); if (failedModules.length !== 0) { debugDependencyInjection && console.warn(`${failedModules.length} modules failed to load, trying again:`, failedModules.map(key => modules[key].name)); const newBatch = {}; failedModules.forEach((key) => { newBatch[key] = modules[key]; }); this.initializeModules(newBatch); } } findModule(type) { return Object.keys(this._modules) .map(key => this._modules[key]) .find(module => module instanceof type); } _debugEventHistory = []; initialize(combatants) { this.initializeNormalizers(combatants); this.initializeAnalyzers(combatants); } initializeAnalyzers(combatants) { this.parseEvents(combatants); this.triggerEvent('initialized'); } parseEvents(events) { if (process.env.NODE_ENV === 'development') { this._debugEventHistory = [ ...this._debugEventHistory, ...events, ]; } events.forEach((event) => { if (this.error) { throw new Error(this.error); } this._timestamp = event.timestamp; // Triggering a lot of events here for development pleasure; does this have a significant performance impact? this.triggerEvent(event.type, event); }); } initializeNormalizers(combatants) { this.activeModules .filter(module => module instanceof EventsNormalizer) .sort((a, b) => a.priority - b.priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(module => { if (module.initialize) { module.initialize(combatants); } }); } normalize(events) { this.activeModules .filter(module => module instanceof EventsNormalizer) .sort((a, b) => a.priority - b.priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(module => { if (module.normalize) { events = module.normalize(events); } }); return events; } /** @type {number} The amount of events parsed. This can reliably be used to determine if something should re-render. */ eventCount = 0; _moduleTime = {}; triggerEvent(eventType, event, ...args) { debugEvents && console.log(eventType, event, ...args); Object.keys(this._modules) .filter(key => this._modules[key].active) .filter(key => this._modules[key] instanceof Analyzer) .sort((a, b) => this._modules[a].priority - this._modules[b].priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(key => { const module = this._modules[key]; if (process.env.NODE_ENV === 'development') { const start = +new Date(); module.triggerEvent(eventType, event, ...args); const duration = +new Date() - start; this._moduleTime[key] = this._moduleTime[key] || 0; this._moduleTime[key] += duration; } else { module.triggerEvent(eventType, event, ...args); } }); this.eventCount += 1; } byPlayer(event, playerId = this.player.id) { return (event.sourceID === playerId); } toPlayer(event, playerId = this.player.id) { return (event.targetID === playerId); } byPlayerPet(event) { return this.playerPets.some(pet => pet.id === event.sourceID); } toPlayerPet(event) { return this.playerPets.some(pet => pet.id === event.targetID); } // TODO: Damage taken from LOTM getPercentageOfTotalHealingDone(healingDone) { return healingDone / this._modules.healingDone.total.effective; } formatItemHealingDone(healingDone) { return `${formatPercentage(this.getPercentageOfTotalHealingDone(healingDone))} % / ${formatNumber(healingDone / this.fightDuration * 1000)} HPS`; } formatItemAbsorbDone(absorbDone) { return `${formatNumber(absorbDone)}`; } getPercentageOfTotalDamageDone(damageDone) { return damageDone / this._modules.damageDone.total.effective; } formatItemDamageDone(damageDone) { return `${formatPercentage(this.getPercentageOfTotalDamageDone(damageDone))} % / ${formatNumber(damageDone / this.fightDuration * 1000)} DPS`; } formatManaRestored(manaRestored) { return `${formatThousands(manaRestored)} mana / ${formatThousands(manaRestored / this.fightDuration * 1000 * 5)} MP5`; } formatTimestamp(timestamp, precision = 0) { return formatDuration((timestamp - this.fight.start_time) / 1000, precision); } generateResults() { const results = new ParseResults(); results.tabs = []; results.tabs.push({ title: 'Timeline', url: 'timeline', order: 2, render: () => ( <TimelineTab start={this.fight.start_time} end={this.currentTimestamp >= 0 ? this.currentTimestamp : this.fight.end_time} historyBySpellId={this.modules.spellHistory.historyBySpellId} globalCooldownHistory={this.modules.globalCooldown.history} channelHistory={this.modules.channeling.history} abilities={this.modules.abilities} isAbilityCooldownsAccurate={this.modules.spellUsable.isAccurate} isGlobalCooldownAccurate={this.modules.globalCooldown.isAccurate} /> ), }); results.tabs.push({ title: <ChangelogTabTitle />, url: 'changelog', order: 1000, render: () => <ChangelogTab />, }); Object.keys(this._modules) .filter(key => this._modules[key].active) .sort((a, b) => this._modules[b].priority - this._modules[a].priority) .forEach(key => { const module = this._modules[key]; if (module.statistic) { const statistic = module.statistic(); if (statistic) { results.statistics.push({ statistic, order: module.statisticOrder, }); } } if (module.item) { const item = module.item(); if (item) { results.items.push(item); } } if (module.tab) { const tab = module.tab(); if (tab) { results.tabs.push(tab); } } if (module.suggestions) { module.suggestions(results.suggestions.when); } }); return results; } } export default CombatLogParser;
src/components/NotFoundPage.js
ferryhinardi/swapii_ass
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/components/Loading.js
PsychoLlama/luminary
import { NavigationActions } from 'react-navigation'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import React from 'react'; import * as startupActions from '../actions/startup'; export class Loading extends React.Component { static propTypes = { getAppState: PropTypes.func.isRequired, navigation: PropTypes.shape({ dispatch: PropTypes.func.isRequired, }).isRequired, }; async componentWillMount() { const { payload } = await this.props.getAppState(); const route = payload.serverUrl ? 'Groups' : 'ServerLink'; // Navigate without adding a back button. const navigate = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: route })], }); this.props.navigation.dispatch(navigate); } render() { return null; } } const mapDispatchToProps = { getAppState: startupActions.getAppState, }; export default connect(null, mapDispatchToProps)(Loading);
docs/src/MainNav.js
jhernandezme/react-materialize
import React from 'react'; import cx from 'classnames'; import store from './store'; import Icon from '../../src/Icon'; import Collapsible from '../../src/Collapsible'; import CollapsibleItem from '../../src/CollapsibleItem'; let cssComponents = { grid: 'Grid', table: 'Table', }; let jsComponents = { collapsible: 'Collapsible', dropdown: 'Dropdown', media: 'Media', modals: 'Modals', tabs: 'Tabs', }; let components = { badges: 'Badges', buttons: 'Buttons', breadcrumbs: 'Breadcrumbs', cards: 'Cards', chips: 'Chips', collections: 'Collections', footer: 'Footer', forms: 'Forms', navbar: 'Navbar', pagination: 'Pagination', preloader: 'Preloader', }; let keys = Object.keys(jsComponents) .concat(Object.keys(cssComponents)) .concat(Object.keys(components)); class Search extends React.Component { constructor(props) { super(props); this.state = {results: [], focused: false}; this.search = this.search.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); } handleFocus() { this.setState({focused: true}); } handleBlur() { this.setState({focused: false}); } search() { let input = new RegExp(this.refs.search.value, 'i'); let results = []; if (input !== '') { keys.forEach(key => { if (input.test(key)) results.push(key); }); this.setState({results: results}); } } capitalize(path) { return path[0].toUpperCase() + path.substr(1); } render() { let classes = { 'search-wrapper': true, card: true, }; classes.focused = this.state.focused; return ( <li className='search'> <div className={cx(classes)}> <input id='search' ref='search' onChange={this.search} onFocus={this.handleFocus} onBlur={this.handleBlur}></input> <Icon>search</Icon> <div className="search-results"> {this.state.results.map(key => { let path = `/${key}.html`; return <a href={path} key={path}>{this.capitalize(key)}</a>; })} </div> </div> </li> ); } } class MainNav extends React.Component { constructor(props) { super(props); this.state = {title: ''}; this.onChange = this.onChange.bind(this); } componentDidMount() { store.on('component', this.onChange); $(".button-collapse").sideNav({edge: 'left'}); } componentWillUnmount() { store.removeListener('component', this.onChange); } onChange(component) { this.setState({ title: component }); } render() { let {location} = this.props; location = location.substr(1).replace(/\.html/, ''); return ( <header> <nav className="top-nav"> <div className="container" > <div className="nav-wrapper"> <a className="page-title"> { this.state.title } </a> </div> </div> </nav> <div className='container'> <a href='#' data-activates='nav-mobile' className='button-collapse top-nav full hide-on-large-only'> <i className='mdi-navigation-menu'/> </a> </div> <ul id='nav-mobile' className='side-nav fixed'> <li className='logo'> <a className='brand-logo' title='React Materialize' id='logo-container' href="https://react-materialize.github.io" > <img src="assets/react-materialize-logo.svg" alt="React Materialize"/> </a> </li> <Search /> <li className="bold"> <a className="waves-effect waves-teal" href="getting-started.html"> Getting started </a> </li> <li className="no-padding" > <Collapsible> <CollapsibleItem header="CSS" expanded={!!~Object.keys(cssComponents).indexOf(location)} className="bold"> <ul> {Object.keys(cssComponents).map(path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}>{cssComponents[path]}</a> </li> ); })} </ul> </CollapsibleItem> <CollapsibleItem header="Components" expanded={!!~Object.keys(components).indexOf(location)} className="bold"> <ul> {Object.keys(components).map( path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}> {components[path]} </a> </li> ); })} </ul> </CollapsibleItem> <CollapsibleItem header="JavaScript" expanded={!!~Object.keys(jsComponents).indexOf(location)} className="bold"> <ul> {Object.keys(jsComponents).map( path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}>{jsComponents[path]}</a> </li> ); })} </ul> </CollapsibleItem> </Collapsible> </li> </ul> </header> ); } } export default MainNav;
src/icons/FiberNewIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FiberNewIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 8H8c-2.21 0-3.98 1.79-3.98 4L4 36c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM17 30h-2.4l-5.1-7v7H7V18h2.5l5 7v-7H17v12zm10-9.49h-5v2.24h5v2.51h-5v2.23h5V30h-8V18h8v2.51zM41 28c0 1.1-.9 2-2 2h-8c-1.1 0-2-.9-2-2V18h2.5v9.01h2.25v-7.02h2.5v7.02h2.25V18H41v10z"/></svg>;} };
app/javascript/mastodon/features/ui/components/column_link.js
lynlynlynx/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;
frontend/src/containers/CreateTarget.js
dionyziz/rupture
import React from 'react'; import { ModalHeader, ModalTitle, ModalClose, ModalBody, ModalFooter } from 'react-modal-bootstrap'; import { Form } from 'react-bootstrap'; import axios from 'axios'; export default class CreateTarget extends React.Component { handleSubmit = (event) => { let method; if (this.refs.method1.checked) { method = parseInt(this.refs.method1.value, 10); } else { method = parseInt(this.refs.method2.value, 10); } event.preventDefault(); axios.post('/breach/target', { name: this.refs.name.value, endpoint: this.refs.url.value, prefix: this.refs.prefix.value, alphabet: this.refs.secral.value, secretlength: this.refs.length.value, alignmentalphabet: this.refs.alignal.value, recordscardinality: this.refs.card.value, method: method }) .then(res => { let target_name = res.data.target_name; console.log(res); this.props.onUpdate(target_name); }) .catch(error => { console.log(error); }); } render() { return( <div> <ModalHeader> <ModalClose type='button' className='btn btn-default' onClick={ this.props.onClose }>Close</ModalClose> <ModalTitle> Create Target </ModalTitle> </ModalHeader> <ModalBody> <div className='row'> <div className='col-xs-offset-1 col-xs-11'> <Form onSubmit={ this.handleSubmit }> <div className='form-group'> <label htmlFor='name' className='col-xs-5 progressmargin'>Name:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='name'/> </div> </div> <div className='form-group'> <label htmlFor='url' className='col-xs-5 progressmargin'>Endpoint url:</label> <div className='col-xs-6 progressmargin'> <input type='url' className='form-control' ref='url'/> </div> </div> <div className='form-group'> <label htmlFor='prefix' className='col-xs-5 progressmargin'>Known prefix:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='prefix'/> </div> </div> <div className='form-group'> <label htmlFor='length' className='col-xs-5 progressmargin'>Secret length:</label> <div className='col-xs-6 progressmargin'> <input type='number' className='form-control' ref='length'/> </div> </div> <div className='form-group'> <label htmlFor='secral' className='col-xs-5 progressmargin'>Secret Alphabet:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='secral'/> </div> </div> <div className='form-group'> <label htmlFor='alignal' className='col-xs-5 progressmargin'>Alignment Alphabet:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' placeholder='abcdefghijklmnopqrstuvwxyz' ref='alignal' /> </div> </div> <div className='form-group'> <label htmlFor='card' className='col-xs-5 progressmargin'>Record cardinality:</label> <div className='col-xs-6 progressmargin'> <input type='number' className='form-control' defaultValue='1' ref='card'/> </div> </div> <div className='form-group'> <label htmlFor='methods' className='col-xs-5 progressmargin'>Method:</label> <div className='radio' name='methods'> <label className='col-xs-4 serialmargin'> <input type='radio' name='method' ref='method1' value='1' defaultChecked/>Serial </label> </div> <div className='col-xs-5'></div> <div className='radio'> <label className='col-xs-4 dividemargin'> <input type='radio' name='method' ref='method2' value='2' />Divide &amp; Conquer </label> </div> </div> </Form> </div> </div> </ModalBody> <ModalFooter> <input type='submit' className='btn btn-default' value='Submit' onClick={ (event) => { this.handleSubmit(event); this.props.onClose(); }}> </input> </ModalFooter> </div> ); } }
app/jsx/external_apps/components/Lti2ReregistrationUpdateModal.js
venturehive/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import I18n from 'i18n!external_tools' import React from 'react' import PropTypes from 'prop-types' import Modal from 'react-modal' import store from 'jsx/external_apps/lib/ExternalAppsStore' export default React.createClass({ displayName: 'Lti2ReregistrationUpdateModal', propTypes: { tool: PropTypes.object.isRequired, closeHandler: PropTypes.func, canAddEdit: PropTypes.bool.isRequired }, getInitialState() { return { modalIsOpen: false } }, openModal(e) { e.preventDefault(); this.setState({modalIsOpen: true}); }, closeModal(cb) { if (typeof cb === 'function') { this.setState({modalIsOpen: false}, cb); } else { this.setState({modalIsOpen: false}); } }, acceptUpdate(e) { e.preventDefault(); this.closeModal(() => { store.acceptUpdate(this.props.tool); }); }, dismissUpdate(e) { e.preventDefault(); this.closeModal(() => { store.dismissUpdate(this.props.tool); }); }, render() { return ( <Modal className="ReactModal__Content--canvas ReactModal__Content--mini-modal" overlayClassName="ReactModal__Overlay--canvas" isOpen={this.state.modalIsOpen} onRequestClose={this.closeModal}> <div className="ReactModal__Layout"> <div className="ReactModal__Header"> <div className="ReactModal__Header-Title"> <h4>{I18n.t('Update %{tool}', {tool: this.props.tool.name})}</h4> </div> <div className="ReactModal__Header-Actions"> <button className="Button Button--icon-action" type="button" onClick={this.closeModal}> <i className="icon-x"></i> <span className="screenreader-only">Close</span> </button> </div> </div> <div className="ReactModal__Body"> {I18n.t('Would you like to accept or dismiss this update?')} </div> <div className="ReactModal__Footer"> <div className="ReactModal__Footer-Actions"> <button ref="btnClose" type="button" className="Button" onClick={this.closeModal}>{I18n.t('Close')}</button> <button ref="btnDelete" type="button" className="Button Button--danger" onClick={this.dismissUpdate}>{I18n.t('Dismiss')}</button> <button ref="btnAccept" type="button" className="Button Button--primary" onClick={this.acceptUpdate}>{I18n.t('Accept')}</button> </div> </div> </div> </Modal> ); } });
app/react-icons/fa/exclamation.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaExclamation extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m24.4 27.9v5q0 0.5-0.4 1t-1 0.4h-5.7q-0.6 0-1-0.4t-0.4-1v-5q0-0.6 0.4-1t1-0.5h5.7q0.6 0 1 0.5t0.4 1z m0.7-23.6l-0.6 17.1q0 0.6-0.5 1t-1 0.5h-5.7q-0.6 0-1-0.5t-0.5-1l-0.6-17.1q0-0.6 0.4-1t1-0.4h7.1q0.6 0 1 0.4t0.4 1z"/></g> </IconBase> ); } }
static/js/components/LoginForm.js
wolendranh/movie_radio
import { Router, Link, browserHistory} from 'react-router'; import {render} from 'react-dom'; import React from 'react'; import $ from 'jquery'; import {login} from '../auth.jsx' // import validator from 'validator'; // TODO: replace validator or make it accessible from import statement class LoginForm extends React.Component { // TODO: divide into smaller reusable components(form, field etc.) constructor(props){ super(props); this.state = { username: 'Ваша_Бармаглот_пошта@mail.com', password: 'Ваш Бармаглот пароль', passwordError: false, usernameError: false, loginError: undefined }; } componentWillMount(){ document.body.style.backgroundColor = "white"; } handlePasswordChange = (e) => { this.setState({ passwordError: this.validateField(this.state.password, validator.isLength, 4) ? false: true}); this.setState({password: e.target.value}); } handleUsernameChange = (e) => { this.setState({username: e.target.value}); this.setState({usernameError: this.validateField(this.state.username, validator.isEmail) ? false: true}); } validateField(data, validatorClass, args){ if (typeof(args) !== 'undefined'){ return validatorClass(data, args); }else{ return validatorClass(data); } } loginHasErrors(){ return 'form-group'+((this.state.usernameError) ? ' has-error': ''); } passwordHasErrors(){ return 'form-group'+((this.state.passwordError) ? ' has-error': ''); } handleSubmit = (e) => { e.preventDefault(); if (this.state.passwordError || this.state.usernameError){ return true } $.ajax({ url: this.props.route.url, dataType: 'json', type: 'POST', data: {'username': this.state.username, 'password': this.state.password}, success: function(data) { localStorage.token = data.token; login(this.state.username, this.state.password); browserHistory.push('/admin'); }.bind(this), error: function(xhr, status, err) { // TODO: handle setting correct server side error into UI this.setState({loginError: err.toString()}); console.error(this.props.route.url, status, err.toString()); }.bind(this) }); } render(){ return ( <div className="wrapper"> <form className="form-signin" method="post" role="form" onSubmit={this.handleSubmit}> <h2 className="form-signin-heading text-center">Бармаглот Адмін</h2> <div className={ this.loginHasErrors() }> <input type="text" className="form-control" onChange={this.handleUsernameChange} placeholder={ this.state.username } name="username" id="login" required=""/> { this.state.usernameError ? <label className="control-label" htmlFor="login">Логін повинен бути адресою електронної пошти</label> :null} </div> <div className={ this.passwordHasErrors() }> <input type="password" className="form-control" onChange={this.handlePasswordChange} placeholder={ this.state.password } id="password" name="password" required=""/> { this.state.passwordError ? <label className="control-label" htmlFor="password">Занадто короткий</label> :null } </div> { this.state.loginError ? <div className="form-group has-error'"> <label className="control-label" for="password">{this.state.loginError}</label> </div> :null } <button type="submit" className="btn btn-lg btn-primary btn-block">Увійти</button> </form> </div> ) } }; export default LoginForm;
lib/cli/generators/REACT/template/stories/Button.js
nfl/react-storybook
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import PropTypes from 'prop-types'; import React from 'react'; const buttonStyles = { border: '1px solid #eee', borderRadius: 3, backgroundColor: '#FFFFFF', cursor: 'pointer', fontSize: 15, padding: '3px 10px', margin: 10, }; const Button = ({ children, onClick }) => <button style={buttonStyles} onClick={onClick}> {children} </button>; Button.propTypes = { children: PropTypes.string.isRequired, onClick: PropTypes.func, }; Button.defaultProps = { onClick: () => {}, }; export default Button;
packages/reactor-kitchensink/src/examples/FormFields/URLField/URLField.js
dbuhrman/extjs-reactor
import React from 'react'; import { FormPanel, URLField } from '@extjs/ext-react'; Ext.require('Ext.data.validator.Url'); export default function UrlFieldExample() { return ( <FormPanel shadow> <URLField placeholder="http://www.domain.com" label="URL" width="200" validators="url" /> </FormPanel> ) }
index.android.js
vinicius-ov/Livefy
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class Livefyy extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('Livefyy', () => Livefyy);
test/test_helper.js
antzu/authenticationApp
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/VideoPlayer.js
MozillaDevelopers/playground
import React from 'react'; import PropTypes from 'prop-types'; // components import ModalVideo from 'react-modal-video'; // CSS import '../../node_modules/react-modal-video/scss/modal-video.scss'; // images import play from './img/play.svg'; class VideoPlayer extends React.Component { constructor() { super(); this.state = { isOpen: false, }; } openModal = () => { this.setState({ isOpen: true, }); } render() { return ( <div className="video-player"> <ModalVideo channel="youtube" isOpen={this.state.isOpen} videoId={this.props.videoId} onClose={() => this.setState({ isOpen: false })} /> <span onClick={this.openModal}> <span className="h2 video-player__text">Launch Video Player</span> <img className="video-player__icon" src={play} alt="play icon" /> </span> </div> ); } } VideoPlayer.propTypes = { videoId: PropTypes.string.isRequired, }; export default VideoPlayer;
src/components/Post/Meta/Meta.js
apalhu/website
// @flow strict import React from 'react'; import moment from 'moment'; import styles from './Meta.module.scss'; type Props = { date: string }; const Meta = ({ date }: Props) => ( <div className={styles['meta']}> <p className={styles['meta__date']}>Published {moment(date).format('D MMM YYYY')}</p> </div> ); export default Meta;