path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
pages/catalog.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import {flowRight, get} from 'lodash' import getConfig from 'next/config' import {_get, _post} from '../lib/fetch' import {isObsolete} from '../lib/catalog' import attachI18n from '../components/hoc/attach-i18n' import withErrors from '../components/hoc/with-errors' import Page from '../components/page' import Meta from '../components/meta' import Content from '../components/content' import Container from '../components/container' import Box from '../components/box' import SearchInput from '../components/search-input' import Warning from '../components/warning' import Header from '../components/catalog/header' import Statistics from '../components/catalog/statistics' import Harvests from '../components/catalog/harvests' import Organizations from '../components/catalog/organizations' const {publicRuntimeConfig: { GEODATA_API_URL }} = getConfig() class CatalogPage extends React.Component { static propTypes = { catalog: PropTypes.shape({ name: PropTypes.string.isRequired, metrics: PropTypes.object }), harvests: PropTypes.array.isRequired, t: PropTypes.func.isRequired, tReady: PropTypes.bool.isRequired } static defaultProps = { catalog: null } static async getInitialProps({query}) { return { catalog: await _get(`${GEODATA_API_URL}/catalogs/${query.cid}`), harvests: await _get(`${GEODATA_API_URL}/services/${query.cid}/synchronizations`) } } runHarvest = () => { const {catalog} = this.props return _post(`${GEODATA_API_URL}/services/${catalog._id}/sync`) } render() { const {catalog, harvests, t, tReady} = this.props const organizationCounts = get(catalog, 'metrics.datasets.counts.organizations') return ( <Page ready={tReady}> {() => ( <> <Meta title={t('details.title', {name: catalog.name})} /> <Content clouds> <Container> <Box> <Header catalog={catalog} /> {isObsolete(catalog) && ( <Warning>{t('common:catalog.obsolete')}</Warning> )} {catalog.metrics && ( <Statistics metrics={catalog.metrics} /> )} <h3>{t('details.harvests.title')}</h3> <Harvests harvests={harvests} catalog={catalog} runHarvest={this.runHarvest} /> <h3>{t('details.search')}</h3> <SearchInput hasButton defaultQuery={{ catalog: catalog.name }} /> {organizationCounts && ( <> <h3>{t('details.organizations')}</h3> <Organizations catalogName={catalog.name} organizationCounts={organizationCounts} /> </> )} </Box> </Container> <style jsx>{` h3 { margin: 2.6em 0 1.4em; } `}</style> </Content> </> )} </Page> ) } } export default flowRight( attachI18n('catalogs'), withErrors )(CatalogPage)
node_modules/native-base/Components/Widgets/Icon.js
paulunits/tiptap
/* @flow */ 'use strict'; import React from 'react'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import Icon from 'react-native-vector-icons/Ionicons'; export default class IconNB extends NativeBaseComponent { getInitialStyle() { return { icon: { fontSize: this.getTheme().iconFontSize, color: this.getContextForegroundColor() } } } prepareRootProps() { var defaultProps = { style: this.getInitialStyle().icon }; return computeProps(this.props, defaultProps); } render() { return( <Icon {...this.prepareRootProps()}/> ); } }
src/components/Feedback/Feedback.js
Rockyluoqi/map_realtime_render
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.scss'; class Feedback extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit" >Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new" >Report an issue</a> </div> </div> ); } } export default withStyles(Feedback, s);
milestones/07-css-modules/After/src/carousel.js
jaketrent/react-drift
import PropTypes from 'prop-types' import React from 'react' import styleable from 'react-styleable' import css from './carousel.module.css' function renderSlides(props) { return React.Children.map(props.children, (slide, i) => { return React.cloneElement(slide, { style: { ...slide.props.style, width: props.width, left: props.width * (i - props.showIndex) } }) }) } function Carousel(props) { return ( <div className={props.css.root}> {renderSlides(props)} {props.nav} </div> ) } Carousel.propTypes = { nav: PropTypes.node.isRequired, showIndex: PropTypes.number, width: PropTypes.number } export default styleable(css)(Carousel)
app/app.js
Frai/Events
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import FontFaceObserver from 'fontfaceobserver'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; import { MuiThemeProvider } from 'material-ui/styles'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-webpack-loader-syntax */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions /* eslint-enable import/no-webpack-loader-syntax */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import routes import createRoutes from './routes'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <MuiThemeProvider> <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider> </MuiThemeProvider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/svg-icons/navigation/subdirectory-arrow-left.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationSubdirectoryArrowLeft = (props) => ( <SvgIcon {...props}> <path d="M11 9l1.42 1.42L8.83 14H18V4h2v12H8.83l3.59 3.58L11 21l-6-6 6-6z"/> </SvgIcon> ); NavigationSubdirectoryArrowLeft = pure(NavigationSubdirectoryArrowLeft); NavigationSubdirectoryArrowLeft.displayName = 'NavigationSubdirectoryArrowLeft'; NavigationSubdirectoryArrowLeft.muiName = 'SvgIcon'; export default NavigationSubdirectoryArrowLeft;
app/scripts/containers/withDrawerState.js
adzialocha/hoffnung3000
import React from 'react' import { connect } from 'react-redux' import { collapseAll, toggleNavigation, toggleSidebar } from '../actions/drawer' export default function withDrawerState(WrappedComponent) { function mapStateToProps(state) { return { ...state.drawer, } } return connect(mapStateToProps, { collapseAll, toggleNavigation, toggleSidebar, })(props => { return <WrappedComponent {...props} /> }) }
docs/src/examples/modules/Search/Types/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' const SearchTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Standard' description='A search can display a set of results.' examplePath='modules/Search/Types/SearchExampleStandard' /> <ComponentExample title='Standard (Custom Render)' description='A search can have a custom rendering.' examplePath='modules/Search/Types/SearchExampleStandardCustom' /> <ComponentExample title='Category' description='A search can display results from remote content ordered by categories.' examplePath='modules/Search/Types/SearchExampleCategory' /> <ComponentExample title='Category (Custom Render)' description='A category search can have a custom rendering.' examplePath='modules/Search/Types/SearchExampleCategoryCustom' /> </ExampleSection> ) export default SearchTypesExamples
src/routes/report/index.js
ynu/ecard-wxe
import React from 'react'; import Report from './Report'; import { getShopBill as getDailyBill } from '../../actions/daily'; import { getShopBill as getMonthlyBill } from '../../actions/monthly'; export default { path: '/shop/:shopId/report/:accDate', async action({ params }) { let title = '云南大学一卡通日账单'; let getReport = getDailyBill; if (params.accDate.length === 6) { title = '云南大学一卡通月账单'; getReport = getMonthlyBill; } return { title, component: <Report {...params} getReport={getReport} />, }; }, };
src/Parser/Priest/Discipline/Modules/Features/PurgeTheWicked.js
enragednuke/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import Enemies from 'Parser/Core/Modules/Enemies'; import SuggestionThresholds from '../../SuggestionThresholds'; class PurgeTheWicked extends Analyzer { static dependencies = { enemies: Enemies, }; dotSpell; on_initialized() { if(this.owner.modules.combatants.selected.hasTalent(SPELLS.PURGE_THE_WICKED_TALENT.id)) { this.dotSpell = SPELLS.PURGE_THE_WICKED_BUFF; } else { this.dotSpell = SPELLS.SHADOW_WORD_PAIN; } } get uptime() { return this.enemies.getBuffUptime(this.dotSpell.id) / this.owner.fightDuration; } suggestions(when) { const uptime = this.uptime || 0; when(uptime).isLessThan(SuggestionThresholds.PURGE_THE_WICKED_UPTIME.minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your <SpellLink id={this.dotSpell.id} /> uptime can be improved.</span>) .icon(this.dotSpell.icon) .actual(`${formatPercentage(uptime)}% uptime`) .recommended(`>${Math.round(formatPercentage(recommended))}% is recommended`) .regular(SuggestionThresholds.PURGE_THE_WICKED_UPTIME.regular).major(SuggestionThresholds.PURGE_THE_WICKED_UPTIME.major); }); } statistic() { const uptime = this.uptime || 0; return ( <StatisticBox icon={<SpellIcon id={this.dotSpell.id} />} value={`${formatPercentage(uptime)} %`} label={`${this.dotSpell.name} Uptime`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(10); } export default PurgeTheWicked;
src/components/player-badge.js
orouvinen/dnf-ranks-frontend
import React, { Component } from 'react'; import EloChart from './elo-chart'; class PlayerBadge extends Component { matchWinCount() { return this.props.matches .filter(m => m.winner === this.props.player.nick) .length; } winPercentage() { return this.matchWinCount() / this.props.matches.length * 100; } render() { const player = this.props.player; const matches = this.props.matches; if (matches.length === 0) return ( <div className="player-badge"> <div> No matches played by <strong>{player.nick}</strong> </div> </div>); // Get elo history for chart display const ratings = matches .map(match => match.player1.match_rating) .reverse(); // Append player current rating to complete rating history ratings.push(player.rating); return ( <div className="player-badge"> <h1>{player.nick}</h1> <div> <div>Elo: {player.rating}</div> <div>{this.props.matches.length} matches played (Win %: {this.winPercentage().toFixed(1)}) </div> </div> <div style={{backgroundColor:"white"}}> <EloChart ratings={ratings} /> </div> </div> ); } } export default PlayerBadge;
src/components/common/svg-icons/action/account-box.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBox = (props) => ( <SvgIcon {...props}> <path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"/> </SvgIcon> ); ActionAccountBox = pure(ActionAccountBox); ActionAccountBox.displayName = 'ActionAccountBox'; ActionAccountBox.muiName = 'SvgIcon'; export default ActionAccountBox;
src/components/Navigation/index.js
happyboy171/Feeding-Fish-View-
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { Nav, NavItem, NavDropdown, MenuItem, ProgressBar, } from 'react-bootstrap'; import Navbar, {Brand} from 'react-bootstrap/lib/Navbar'; import history from '../../core/history'; import $ from "jquery"; const logo = require('./observelogo.png'); const NavBarData = { messages : [{cageid: 1, timeAlerted: new Date("02/10/2017")}], // Progressbar =[success(green),info(blue),warning(yellow),danger(red)] cageStatus : [{cageid: 1, percentagefed:80, lastFeed:"12:12", nextFeed:"4:16" , cagestatus: "success"}, {cageid: 2, percentagefed:25, lastFeed:"11:11", nextFeed:"13:40", cagestatus: "warning"}, {cageid: 3, percentagefed:50, lastFeed:"8:59", nextFeed:"14:13", cagestatus: "success"}, {cageid: 4, percentagefed:8, lastFeed:"7:30", nextFeed:"17:35", cagestatus: "danger"} ] } function Navigation() { function timeSince(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } function renderCageStatus() { let cages = NavBarData.cageStatus; return cages.map( function( element, index ) { return ( <MenuItem style={ {width: 200} } eventKey={index} key={index}> <div> <p> <strong>Cage {element.cageid}</strong> <span className="pull-right text-muted">{element.percentagefed}% Complete</span> </p> <div> <ProgressBar bsStyle={element.cagestatus} now={element.percentagefed} /> </div> </div> </MenuItem>) }); }; function renderMessagesStatus() { let messages = NavBarData.messages, toRet = []; messages.forEach( function( element, index ) { toRet.push( <MenuItem style={ {width: 300} } eventKey={index} key={index}> <div> <strong>Cage {element.cageid}</strong> <span className="pull-right text-muted"> <em>{timeSince(element.timeAlerted)} ago</em> </span> </div> <div>Cage alert!</div> </MenuItem> ); toRet.push(<MenuItem key={index+messages.length} divider />); }); toRet.pop(); return toRet; }; return ( <div id="wrapper" className="content"> <Navbar fluid={true} style={ {margin: 0} }> <Brand> <span> <img src={logo}/> <button type="button" className="navbar-toggle" onClick={() => {toggleMenu();}} style={{position: 'absolute', right: 0, top: 0}}> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> </span> </Brand> <ul className="nav navbar-top-links navbar-right"> <NavDropdown bsClass="dropdown" title={<span><i className="fa fa-envelope fa-fw"></i></span>} id="navDropdown1"> {renderMessagesStatus()} </NavDropdown> <NavDropdown title={<span><i className="fa fa-tasks fa-fw"></i> </span>} id = 'navDropdown2222'> {renderCageStatus()} </NavDropdown> <NavDropdown title={<i className="fa fa-user fa-fw"></i> } id = 'navDropdown4'> <MenuItem eventKey="1"> <span> <i className="fa fa-user fa-fw"></i> User Profile </span> </MenuItem> <MenuItem eventKey="2"> <span><i className="fa fa-gear fa-fw"></i> Settings </span> </MenuItem> <MenuItem divider /> <MenuItem eventKey = "4" onClick = {(event) => { history.push('/login');}}> <span> <i className = "fa fa-sign-out fa-fw" /> Logout </span> </MenuItem> </NavDropdown> </ul> <ul className="nav navbar-nav navbar-left collapse navbar-collapse"> <li><a href="/">Dashboard</a></li> <li><a href="/live">Live</a></li> <li><a href="/finances">Finances</a></li> <li><a href="/logs">Logs</a></li> </ul> </Navbar> </div> ); } function toggleMenu(){ if($(".navbar-collapse").hasClass('collapse')){ $(".navbar-collapse").removeClass('collapse'); } else{ $(".navbar-collapse").addClass('collapse'); } } export default Navigation;
pkg/interface/groups/src/js/api.js
jfranklin9000/urbit
import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'lodash'; import { uuid } from '/lib/util'; import { store } from '/store'; class UrbitApi { setAuthTokens(authTokens) { this.authTokens = authTokens; this.bindPaths = []; this.contactHook = { edit: this.contactEdit.bind(this) }; this.contactView = { create: this.contactCreate.bind(this), delete: this.contactDelete.bind(this), remove: this.contactRemove.bind(this), share: this.contactShare.bind(this) }; this.group = { add: this.groupAdd.bind(this), delete: this.groupRemove.bind(this) }; this.invite = { accept: this.inviteAccept.bind(this), decline: this.inviteDecline.bind(this) }; } bind(path, method, ship = this.authTokens.ship, app, success, fail, quit) { this.bindPaths = _.uniq([...this.bindPaths, path]); window.subscriptionId = window.urb.subscribe(ship, app, path, (err) => { fail(err); }, (event) => { success({ data: event, from: { ship, path } }); }, (qui) => { quit(qui); }); } action(appl, mark, data) { return new Promise((resolve, reject) => { window.urb.poke(ship, appl, mark, data, (json) => { resolve(json); }, (err) => { reject(err); }); }); } contactViewAction(data) { return this.action("contact-view", "json", data); } contactCreate(path, ships = [], title, description) { return this.contactViewAction({ create: { path, ships, title, description } }); } groupAdd(path, ships = []) { return this.action("group-store", "group-action", { add: { members: ships, path } }); } groupRemove(path, ships) { return this.action("group-store", "group-action", { remove: { members: ships, path } }) } contactShare(recipient, path, ship, contact) { return this.contactViewAction({ share: { recipient, path, ship, contact } }); } contactDelete(path) { return this.contactViewAction({ delete: { path }}); } contactRemove(path, ship) { return this.contactViewAction({ remove: { path, ship } }); } contactHookAction(data) { return this.action("contact-hook", "contact-action", data); } contactEdit(path, ship, editField) { /* editField can be... {nickname: ''} {email: ''} {phone: ''} {website: ''} {notes: ''} {color: 'fff'} // with no 0x prefix {avatar: null} {avatar: {url: ''}} */ return this.contactHookAction({ edit: { path, ship, 'edit-field': editField } }); } inviteAction(data) { return this.action("invite-store", "json", data); } inviteAccept(uid) { return this.inviteAction({ accept: { path: '/contacts', uid } }); } inviteDecline(uid) { return this.inviteAction({ decline: { path: '/contacts', uid } }); } metadataAction(data) { console.log(data); return this.action("metadata-hook", "metadata-action", data); } metadataAdd(appPath, groupPath, title, description, dateCreated, color) { let creator = `~${window.ship}`; return this.metadataAction({ add: { "group-path": groupPath, resource: { "app-path": appPath, "app-name": "contacts" }, metadata: { title, description, color, 'date-created': dateCreated, creator } } }) } setSelected(selected) { store.handleEvent({ data: { local: { selected: selected } } }) } } export let api = new UrbitApi(); window.api = api;
app/app.js
hukid/shootingstudio
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; // TODO constrain eslint import/no-unresolved rule to this block // Load the manifest.json file and the .htaccess file import 'file?name=[name].[ext]!./manifest.json'; // eslint-disable-line import/no-unresolved import 'file?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/no-unresolved // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import useScroll from 'react-router-scroll'; import configureStore from './store'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/lib/sanitize.css'; // Import bootstrap css import 'static/stylesheet/bootstrap.min.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; ReactDOM.render( <Provider store={store}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </Provider>, document.getElementById('app') ); // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed // import { install } from 'offline-plugin/runtime'; // install();
imports/ui/components/profile/profile-header.js
irvinlim/free4all
import React from 'react'; import Chip from 'material-ui/Chip'; import Link from '../../layouts/link'; import * as Colors from 'material-ui/styles/colors'; import * as UsersHelper from '../../../util/users'; import * as IconsHelper from '../../../util/icons'; const makeChip = (role, index) => { let label; if (role == "moderator") { label = "Mod"; } else if (role == "admin") { label = "Admin"; } else { return null; } return ( <Chip key={index} backgroundColor="#8595b7" labelStyle={{ fontSize: 12, textTransform: 'uppercase', color: "#fff", lineHeight: "24px", padding: "0 8px" }}> { label } </Chip> ); }; const makeUrlIcon = (icon, url) => ( <Link className="social-link" to={url} style={{ margin: "0 5px" }}> { IconsHelper.icon(icon) } </Link> ); const communityDisplay = (community, isHome=false) => ( <span key={community._id} className="community-display"> { isHome ? IconsHelper.icon("home", { color: "#9c9c9c", fontSize: "14px", marginRight: 3 }) : null } { community.name } </span> ); export const ProfileHeader = ({ user, shareCount, ratingPercent, homeCommunity, userCommunities }) => ( <div className="profile-header flex-row"> <div className="col-xs-4 col-sm-2"> { UsersHelper.getAvatar(user, 240, { width: "100%", height: 'auto' }) } </div> <div className="col-xs-8 col-sm-10"> <h1> { UsersHelper.getFullName(user) } { user.roles ? <span className="role-chips">{ user.roles.map(makeChip) }</span> : null } </h1> <h5> { homeCommunity ? communityDisplay(homeCommunity, true) : null } { userCommunities ? userCommunities.map(comm => communityDisplay(comm, false)) : null } </h5> <div className="social-links"> { user.profile.website ? makeUrlIcon('fa fa-link', user.profile.website) : null } { user.profile.facebookId ? makeUrlIcon('fa fa-facebook-f', `https://facebook.com/${user.profile.facebookId}`) : null } { user.profile.twitterId ? makeUrlIcon('fa fa-twitter', `https://twitter.com/${user.profile.twitterId}`) : null } { user.profile.instagramId ? makeUrlIcon('fa fa-instagram', `https://www.instagram.com/${user.profile.instagramId}`) : null } { user.profile.googlePlusId ? makeUrlIcon('fa fa-google-plus', `https://plus.google.com/+${user.profile.googlePlusId}`) : null } </div> <p style={{ color: Colors.grey600 }}>{ UsersHelper.getBio(user) }</p> <ul className="user-stats"> <li><strong>{ shareCount }</strong> giveaways shared</li> <li><strong>{ ratingPercent }%</strong> approval rating</li> </ul> </div> </div> );
src/components/GridHeader.js
sateez/salestracker
import React from 'react'; const GridHeader = (props) => { return ( <div className='grid-row row' > <div className='grid-header-row-column column-image col-sm-4'>product</div> <div className='grid-header-row-column column-code col-sm-1'>product id </div> <div className='col-sm-2'> <div className="col-sm-12 grid-header-row-column">Estimated Sales</div> <div className='grid-header-row-column column-est-daily col-sm-6'>daily</div> <div className='grid-header-row-column column-est-monthly col-sm-6'>montly</div> </div> <div className='col-sm-2'> <div className="col-sm-12 grid-header-row-column">Estimated revenue</div> <div className='grid-header-row-column column-est-rev-unit col-sm-6'>per unit</div> <div className='grid-header-row-column column-est-rev-monthly col-sm-6'>monthly</div> </div> <div className='grid-header-row-column column-goto col-sm-1'>&nbsp;</div> <div className='grid-header-row-column column-show-hide col-sm-1'>&nbsp;</div> <div className='grid-header-row-column column-remove col-sm-1'>&nbsp;</div> </div> ) } export default GridHeader;
client/src/components/MyDrawer.js
juandaco/voting-app
import React from 'react'; import { Drawer, Navigation, Badge, Icon } from 'react-mdl'; const MyDrawer = ( { username, userPollCount, showUserDashboard, showAllPolls, loginDialog, logoutUser, aboutDialog, }, ) => { const divPointer = { cursor: 'pointer' }; return ( <Drawer title="Pollster"> <Navigation> <div style={username ? {width: 208} : divPointer} onClick={username ? null : loginDialog} > <Icon name="account_circle" /> <span className="drawer-link">{username || 'Login'}</span> </div> <hr style={{ pointerEvents: 'none', marginTop: 10 }} className="separator" /> {username ? <div style={divPointer} onClick={showUserDashboard}> <Icon name="home" /> <Badge text={userPollCount} style={{marginLeft: -12, marginTop: -10}}> </Badge> <span className="drawer-link" style={{ marginLeft: 5 }}> My Polls </span> </div> : null} <div style={divPointer} onClick={showAllPolls}> <Icon name="inbox" /> <span className="drawer-link">All Polls</span> </div> {username ? <div style={divPointer} onClick={logoutUser}> <Icon name="exit_to_app" /> <span className="drawer-link">Logout</span> </div> : null} <div style={divPointer} onClick={aboutDialog}> <Icon name="help_outline" /> <span className="drawer-link">About</span> </div> </Navigation> </Drawer> ); }; export default MyDrawer;
src/components/Dialogs/EditMediaDialog/index.js
u-wave/web
import cx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import Dialog from '@mui/material/Dialog'; import DialogTitle from '@mui/material/DialogTitle'; import DialogContent from '@mui/material/DialogContent'; import IconButton from '@mui/material/IconButton'; import formatDuration from 'format-duration'; import ArtistIcon from '@mui/icons-material/Headset'; import TitleIcon from '@mui/icons-material/MusicNote'; import StartIcon from '@mui/icons-material/PlayArrow'; import EndIcon from '@mui/icons-material/Stop'; import SwapArtistTitleIcon from '@mui/icons-material/SwapHoriz'; import DialogCloseAnimation from '../../DialogCloseAnimation'; import Form from '../../Form'; import FormGroup from '../../Form/Group'; import Button from '../../Form/Button'; import TextField from '../../Form/TextField'; const { useCallback, useId, useState, } = React; // naive HH:mm:ss → seconds const parseDuration = (str) => str.split(':') .map((part) => parseInt(part.trim(), 10)) .reduce((duration, part) => (duration * 60) + part, 0); const BASE_TAB_INDEX = 1000; function EditMediaDialog({ media, open, bodyClassName, contentClassName, titleClassName, onEditedMedia, onCloseDialog, }) { const { t } = useTranslator(); const id = useId(); const ariaTitle = `${id}-title`; const startFieldId = `${id}-start`; const endFieldId = `${id}-end`; const [errors, setErrors] = useState(null); const [artist, setArtist] = useState(media.artist); const [title, setTitle] = useState(media.title); const [start, setStart] = useState(formatDuration(media.start * 1000)); const [end, setEnd] = useState(formatDuration(media.end * 1000)); const handleSubmit = (e) => { e.preventDefault(); const startSeconds = parseDuration(start); const endSeconds = parseDuration(end); const errorLabels = []; if (Number.isNaN(startSeconds) || startSeconds < 0) { errorLabels.push('invalidStartTime'); } if (Number.isNaN(endSeconds) || endSeconds < 0) { errorLabels.push('invalidEndTime'); } else if (endSeconds < startSeconds) { errorLabels.push('endTimeBeforeStart'); } else if (endSeconds > media.duration) { errorLabels.push('endTimeAfterSongEnd'); } if (errorLabels.length > 0) { setErrors(errorLabels); return; } onEditedMedia({ artist, title, start: startSeconds, end: endSeconds, }); onCloseDialog(); }; const handleChangeArtist = useCallback((event) => { setArtist(event.target.value); }, []); const handleChangeTitle = useCallback((event) => { setTitle(event.target.value); }, []); const handleChangeStart = useCallback((event) => { setStart(event.target.value); }, []); const handleChangeEnd = useCallback((event) => { setEnd(event.target.value); }, []); const handleSwapArtistTitle = useCallback(() => { setArtist(title); setTitle(artist); }, [artist, title]); const artistInput = ( <TextField className="EditMediaDialogGroup-field" placeholder={t('dialogs.editMedia.artistLabel') ?? t('media.artist')} value={artist} onChange={handleChangeArtist} icon={<ArtistIcon htmlColor="#9f9d9e" />} tabIndex={BASE_TAB_INDEX} autoFocus /> ); const artistTitleLabel = ( <div className="EditMediaDialogGroup-label"> <IconButton onClick={handleSwapArtistTitle}> <SwapArtistTitleIcon htmlColor="#9f9d9e" /> </IconButton> </div> ); const titleInput = ( <TextField className="EditMediaDialogGroup-field" placeholder={t('dialogs.editMedia.titleLabel') ?? t('media.title')} value={title} onChange={handleChangeTitle} icon={<TitleIcon htmlColor="#9f9d9e" />} tabIndex={BASE_TAB_INDEX + 1} /> ); const fromLabel = ( // eslint-disable-next-line jsx-a11y/label-has-for <label htmlFor={startFieldId} className="EditMediaDialogGroup-label"> {t('dialogs.editMedia.playFromLabel')} </label> ); const fromInput = ( <TextField id={startFieldId} className="EditMediaDialogGroup-field" placeholder="0:00" value={start} onChange={handleChangeStart} icon={<StartIcon htmlColor="#9f9d9e" />} tabIndex={BASE_TAB_INDEX + 2} /> ); const toLabel = ( // eslint-disable-next-line jsx-a11y/label-has-for <label htmlFor={endFieldId} className="EditMediaDialogGroup-label"> {t('dialogs.editMedia.playToLabel')} </label> ); const toInput = ( <TextField id={endFieldId} className="EditMediaDialogGroup-field" placeholder={formatDuration(media.duration)} value={end} onChange={handleChangeEnd} icon={<EndIcon htmlColor="#9f9d9e" />} tabIndex={BASE_TAB_INDEX + 3} /> ); const form = ( <Form onSubmit={handleSubmit}> {errors && errors.length > 0 && ( <FormGroup> {errors.map((error) => ( <div>{t(`dialogs.editMedia.errors.${error}`)}</div> ))} </FormGroup> )} <div className="EditMediaDialogForm"> <div className="EditMediaDialogForm-column"> <FormGroup className="EditMediaDialogGroup"> {artistInput} </FormGroup> <FormGroup className="EditMediaDialogGroup"> {fromLabel} {fromInput} </FormGroup> </div> <div className="EditMediaDialogForm-separator"> <FormGroup className="EditMediaDialogGroup"> {artistTitleLabel} </FormGroup> <FormGroup className="EditMediaDialogGroup"> {toLabel} </FormGroup> </div> <div className="EditMediaDialogForm-column"> <FormGroup className="EditMediaDialogGroup"> {titleInput} </FormGroup> <FormGroup className="EditMediaDialogGroup"> {toInput} </FormGroup> </div> </div> <FormGroup className="FormGroup--noSpacing"> <Button className="EditMediaDialog-submit"> {t('dialogs.editMedia.save')} </Button> </FormGroup> </Form> ); return ( <DialogCloseAnimation delay={450}> {open ? ( <Dialog classes={{ paper: cx('Dialog', 'EditMediaDialog', contentClassName), }} open={open} onClose={onCloseDialog} aria-labelledby={ariaTitle} > <DialogTitle id={ariaTitle} className={cx('Dialog-title', titleClassName)}> {t('dialogs.editMedia.title')} </DialogTitle> <DialogContent className={cx('Dialog-body', bodyClassName)}> {form} </DialogContent> </Dialog> ) : null} </DialogCloseAnimation> ); } EditMediaDialog.propTypes = { open: PropTypes.bool, media: PropTypes.object, bodyClassName: PropTypes.string, contentClassName: PropTypes.string, titleClassName: PropTypes.string, onEditedMedia: PropTypes.func.isRequired, onCloseDialog: PropTypes.func.isRequired, }; export default EditMediaDialog;
packages/core/upload/admin/src/components/PluginIcon/index.js
wistityhq/strapi
/** * * PluginIcon * */ import React from 'react'; import Landscape from '@strapi/icons/Landscape'; const PluginIcon = () => <Landscape />; export default PluginIcon;
src/SFormSummary.js
thr-consulting/controls
// @flow import React from 'react'; import Form from 'react-formal'; import hash from 'string-hash'; import {Message} from 'semantic-ui-react'; type Props = { otherErrors?: string[], }; /** * Displays a message indicating any errors with the form. Include inside a SForm to automatically read the form's errors. * @class * @property {string[]} otherErrors - An array of additional errors strings to display. */ export default function SFormSummary(props: Props) { const otherErrors = (props.otherErrors) ? (<ul> {props.otherErrors.map(msg => <li key={hash(msg)}>{msg}</li>)} </ul>) : null; return ( <Message error> <Form.Summary/> {otherErrors} </Message> ); }
src/routes.js
SiHeTech/react-templete
import React from 'react'; import { Route } from 'react-router'; import App from './containers/app'; export const routes = ( <Route path="/" component={App} /> ); export default routes;
javascript/tutorial-redux/containers/AddTodo.js
jtwp470/my-programming-learning-book
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
src/components/Tabs/Tabs.js
Galernaya20/galernaya20.com
// @flow import React from 'react' import {Tab, Tabs, TabList, TabPanel} from 'react-tabs' import styled from 'styled-components' const Self = styled.div` .react-tabs__tab-list { margin: 0; padding: 0; list-style-type: none; border-bottom: 1px solid #f1f1f1; } .react-tabs__tab { cursor: pointer; display: inline-block; padding: 10px; } .react-tabs__tab--selected { background-color: #f1f1f1; } ` export type PropsT = { tabs: Array<{title: string, content: {content: string}}>, } export const TabsComponent = ({tabs}: PropsT) => { const tabItems = tabs.map((item, index) => <Tab key={index}>{item.title}</Tab>) const contentItems = tabs.map((item, index) => ( <TabPanel key={index}> <div dangerouslySetInnerHTML={{ __html: item.content.content, }} /> </TabPanel> )) return ( <Self> <Tabs> <TabList>{tabItems}</TabList> {contentItems} </Tabs> </Self> ) }
app/components/connect/sidebar/component.js
mic-fadeev/postglass
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as FavoritesActions from '../../../actions/favorites'; import SidebarItemComponent from './item/component'; const propTypes = { getFavorites: React.PropTypes.func.isRequired, setCurrent: React.PropTypes.func.isRequired, favorites: React.PropTypes.array.isRequired }; class SidebarConnectComponent extends Component { constructor(props) { super(props); this.setCurrent = this.setCurrent.bind(this); } componentWillMount() { this.props.getFavorites(); } setCurrent(itemId) { this.props.setCurrent(itemId); } render() { const { favorites } = this.props; let noFavorits = true; for (const favorit of favorites) { if (favorit.isCurrent) { noFavorits = false; break; } } return ( <nav className="navbar-default navbar-static-side scrollable"> <div className="sidebar-collapse"> <ul className="nav metismenu"> <SidebarItemComponent iconName="New connection" iconClass="fa fa-plus" className={noFavorits && 'active'} setCurrent={this.setCurrent} /> </ul> <hr /> { (favorites.length > 0) && <div> <h3>Favorites</h3> <ul className="nav metismenu"> { favorites.map((item) => ( <SidebarItemComponent key={item.id} item={item} iconName={item.name || item.user} iconClass="fa fa-database" className={item.isCurrent && 'active'} setCurrent={this.setCurrent} /> ) ) } </ul> </div> } </div> </nav> ); } } SidebarConnectComponent.propTypes = propTypes; function mapStateToProps(state) { return { favorites: state.favorites }; } function mapDispatchToProps(dispatch) { return bindActionCreators(FavoritesActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(SidebarConnectComponent);
react_native_frontend/src/components/form/backButton.js
CUNYTech/BudgetApp
import React, { Component } from 'react'; import { TouchableOpacity } from 'react-native'; import Icon from 'react-native-vector-icons/SimpleLineIcons'; export default class BackButton extends Component { render() { return ( <TouchableOpacity key="icon_left" onPress={this.props.onPressIcon} style={styleWrapper.container}> <Icon color="#ffffff" size={25} name={this.props.iconLeft} style={styleWrapper.icon} /> </TouchableOpacity> ); } } const styleWrapper = { container: { zIndex: 1000, position: 'absolute', top: 30, left: 20, }, icon: { opacity: 0.8, }, };
node_modules/react-flexbox-grid/spec/root.js
SerendpityZOEY/Fixr-RelevantCodeSearch
/* global VERSION */ require('./stylesheets/base'); import box from './stylesheets/modules/box'; import React from 'react'; import {Grid, Row, Col} from '../src/index'; const Root = () => ( <div> <h1>React Flexbox Grid <small>Spec {VERSION}</small></h1> <Grid> <Row> <Col xs={12} sm={3} md={2} lg={1}> <div className={box.row} /> </Col> <Col xs={6} sm={6} md={8} lg={10}> <div className={box.row} /> </Col> <Col xs={6} sm={3} md={2} lg={1}> <div className={box.row} /> </Col> </Row> </Grid> </div> ); export default Root;
src/common/components/vanilla/table-interactive/head.js
canonical-websites/build.snapcraft.io
import PropTypes from 'prop-types'; import React from 'react'; import styles from './table.css'; export default function Head(props) { return ( <header className={ styles.head }> { props.children } </header> ); } Head.propTypes = { children: PropTypes.node };
blueocean-material-icons/src/js/components/svg-icons/image/wb-cloudy.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageWbCloudy = (props) => ( <SvgIcon {...props}> <path d="M19.36 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.64-4.96z"/> </SvgIcon> ); ImageWbCloudy.displayName = 'ImageWbCloudy'; ImageWbCloudy.muiName = 'SvgIcon'; export default ImageWbCloudy;
webpack/components/Search/index.js
johnpmitsch/katello
/* eslint-disable import/no-extraneous-dependencies */ import React, { Component } from 'react'; import { ControlLabel } from 'react-bootstrap'; import PropTypes from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import TypeAhead from '../../move_to_pf/TypeAhead/TypeAhead'; import api from '../../services/api'; import { stringIncludes } from './helpers'; class Search extends Component { constructor(props) { super(props); this.state = { items: [] }; this.onInputUpdate = this.onInputUpdate.bind(this); this.onSearch = this.onSearch.bind(this); } componentDidMount() { this.onInputUpdate(); } async onInputUpdate(searchTerm = '') { const items = this.state.items.filter(({ text }) => stringIncludes(text, searchTerm)); if (items.length !== this.state.items.length) { this.setState({ items }); } const params = this.props.getAutoCompleteParams(searchTerm); const autoCompleteParams = [ params.endpoint, params.headers || {}, params.params || {}, ]; if (autoCompleteParams[0] !== '') { const { data } = await api.get(...autoCompleteParams); this.setState({ items: data.filter(({ error }) => !error).map(({ label }) => ({ text: label.trim(), })), }); } } onSearch(search) { if (this.props.updateSearchQuery) this.props.updateSearchQuery(search); this.props.onSearch(search); } render() { const { initialInputValue } = this.props; return ( <div> <ControlLabel srOnly>{__('Search')}</ControlLabel> <TypeAhead items={this.state.items} onInputUpdate={this.onInputUpdate} onSearch={this.onSearch} initialInputValue={initialInputValue} /> </div> ); } } Search.propTypes = { /** Callback function when the "Search" button is pressed: onSearch(searchQuery) */ onSearch: PropTypes.func.isRequired, /** Function returning params for the scoped-search complete api call: getAutoCompleteParams(searchQuery) Should return a shape { headers, params, endpoint }, e.g.: { headers: {}, params: { organization_id, search }, endpoint: '/subscriptions/auto_complete_search' } */ getAutoCompleteParams: PropTypes.func.isRequired, updateSearchQuery: PropTypes.func, initialInputValue: PropTypes.string, }; Search.defaultProps = { updateSearchQuery: undefined, initialInputValue: '', }; export default Search;
project/src/scenes/Blog/components/ArticleImage/ArticleImage.js
boldr/boldr
/* @flow */ import React from 'react'; import classnames from 'classnames'; import { StyleClasses } from '@boldr/ui'; const BASE_ELEMENT = StyleClasses.ARTICLE_IMAGE_WRAP; const BASE_ELEMENT2 = StyleClasses.ARTICLE_IMAGE; const ArticleImage = (props: { imageSrc: string, altText: string, className?: string, imgClass?: string, }) => { const classes = classnames(BASE_ELEMENT, props.className); const classes2 = classnames(BASE_ELEMENT2, props.imgClass); return ( <div className={classes}> <img src={props.imageSrc} alt={props.altText} className={classes2} /> </div> ); }; export default ArticleImage;
src/interface/statistics/components/RadarChart/index.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { scaleLinear, scaleOrdinal } from 'd3-scale'; import { schemeCategory10 } from 'd3-scale-chromatic'; import { lineRadial, curveCardinalClosed, curveLinearClosed } from 'd3-shape'; import SvgWrappingText from './SvgWrappingText'; // This is heavily based on https://gist.github.com/nbremer/21746a9668ffdf6d8242#file-radarchart-js // It was severely cleaned up, updated for the d3 version we use, and modified to behave as a component. // The original code was licensed as "license: mit". These modifications (basically any code not straight from the original) is licensed under the regular license used in this project. If you need a MIT license you should use the code in the above link instead. export function maxDataValue(data) { return data.reduce((dataMax, series) => series.points.reduce((seriesMax, item) => ( Math.max(seriesMax, item.value) ), dataMax), 0); } class RadarChart extends React.Component { static propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, margin: PropTypes.shape({ top: PropTypes.number, right: PropTypes.number, bottom: PropTypes.number, left: PropTypes.number, }), levels: PropTypes.number, maxValue: PropTypes.number, labelFactor: PropTypes.number, wrapWidth: PropTypes.number, opacityArea: PropTypes.number, dotRadius: PropTypes.number, opacityCircles: PropTypes.number, strokeWidth: PropTypes.number, roundStrokes: PropTypes.bool, color: PropTypes.object, data: PropTypes.arrayOf(PropTypes.shape({ color: PropTypes.string, points: PropTypes.arrayOf(PropTypes.shape({ axis: PropTypes.string.isRequired, value: PropTypes.number.isRequired, })).isRequired, })).isRequired, labelFormatter: PropTypes.array.isRequired, }; static defaultProps = { width: 500, //Width of the circle height: 500, //Height of the circle margin: { top: 40, right: 40, bottom: 40, left: 40 }, //The margins of the SVG levels: 3, //How many levels or inner circles should there be drawn maxValue: 0, //What is the value that the biggest circle will represent labelFactor: 1.25, //How much farther than the radius of the outer circle should the labels be placed labelMaxWidth: 60, //The number of pixels after which a label needs to be given a new line opacityArea: 0.35, //The opacity of the area of the blob dotRadius: 4, //The size of the colored circles of each blog opacityCircles: 0.1, //The opacity of the circles of each blob strokeWidth: 2, //The width of the stroke around each blob roundStrokes: false, //If true the area and stroke will follow a round path (cardinal-closed) color: scaleOrdinal(schemeCategory10), //Color function }; render() { const { data, width, height, margin, levels, opacityCircles, labelFactor, labelMaxWidth, roundStrokes, color, opacityArea, strokeWidth, dotRadius, labelFormatter, ...others } = this.props; //If the supplied maxValue is smaller than the actual one, replace by the max in the data const maxValue = Math.max(this.props.maxValue, maxDataValue(data)); //Names of each axis const allAxis = data[0].points.map(i => i.axis); //The number of different axes const total = allAxis.length; //Radius of the outermost circle const radius = Math.min(width / 2, height / 2); //The width in radians of each "slice" const angleSlice = Math.PI * 2 / total; //Scale for the radius const rScale = scaleLinear() .range([0, radius]) .domain([0, maxValue]); //The radial line function const radarLine = lineRadial() .curve(curveLinearClosed) .radius(d => rScale(d.value)) .angle((_, i) => i * angleSlice); if (roundStrokes) { radarLine.curve(curveCardinalClosed); } return ( <svg width={width + margin.left + margin.right} height={height + margin.top + margin.bottom} className="radar" style={{ overflow: 'visible' }} {...others} > <g transform={`translate(${width / 2 + margin.left}, ${height / 2 + margin.top})`}> <defs> <filter id="glow"> <feGaussianBlur stdDeviation={2.5} result="coloredBlur" /> <feMerge> <feMergeNode in="coloredBlur" /> <feMergeNode in="SourceGraphic" /> </feMerge> </filter> </defs> <g className="axisWrapper"> {/* the background circles */} {[...Array(3).keys()].reverse().map(level => ( <circle className="gridCircle" r={radius / levels * (level + 1)} style={{ fill: '#CDCDCD', stroke: '#CDCDCD', strokeOpacity: 0.5, fillOpacity: opacityCircles, filter: 'url(#glow)', }} /> ))} {/* the background circle labels */} {/* don't merge with the above loop since we need text to overlap ALL circles */} {[...Array(3).keys()].reverse().map(level => ( <text className="axisLabel" x={4} y={-(level + 1) * radius / levels} dy="0.4em" style={{ fontSize: 10 }} fill="rgba(200, 200, 200, 0.7)" > {labelFormatter(maxValue * (level + 1) / levels)} </text> ))} {/* Create the straight lines radiating outward from the center */} {allAxis.map((label, i) => ( <g className="axis"> <line className="line" x1={0} y1={0} x2={rScale(maxValue * 1.1) * Math.cos(angleSlice * i - Math.PI / 2)} y2={rScale(maxValue * 1.1) * Math.sin(angleSlice * i - Math.PI / 2)} style={{ stroke: 'white', strokeOpacity: 0.5, strokeWidth: 2, }} /> {/* the labels at the end of each axis */} <SvgWrappingText className="legend" style={{ fontSize: 11 }} textAnchor="middle" dy="0.35em" x={rScale(maxValue * labelFactor) * Math.cos(angleSlice * i - Math.PI / 2)} y={rScale(maxValue * labelFactor) * Math.sin(angleSlice * i - Math.PI / 2)} width={labelMaxWidth} > {label} </SvgWrappingText> </g> ))} {/* Draw the radar chart blobs (value blobs) */} {data.map((series, i) => ( <g className="radarWrapper"> {/* The backgrounds */} <path className="radarArea" d={radarLine(series.points)} style={{ fill: series.color || color(i), fillOpacity: opacityArea, }} /> {/* The outlines */} <path className="radarStroke" d={radarLine(series.points)} style={{ strokeWidth: strokeWidth, stroke: series.color || color(i), fill: 'none', filter: 'url(#glow)', }} /> {/* Circles on the axis to show exact cross over */} {series.points.map((point, pointIndex) => ( <circle className="radarCircle" r={dotRadius} cx={rScale(point.value) * Math.cos(angleSlice * pointIndex - Math.PI / 2)} cy={rScale(point.value) * Math.sin(angleSlice * pointIndex - Math.PI / 2)} style={{ fill: series.color || color(i), fillOpacity: 0.8, }} /> ))} </g> ))} </g> </g> </svg> ); } } export default RadarChart; // TODO: Tooltips // export default function RadarChart(id, data, options) { // //Append the circles // blobWrapper.selectAll('.radarCircle') // .data(function (d, i) { // return d; // }) // .enter().append('circle') // .attr('class', 'radarCircle') // .attr('r', cfg.dotRadius) // .attr('cx', function (d, i) { // return rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2); // }) // .attr('cy', function (d, i) { // return rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2); // }) // .style('fill', function (d, i, j) { // return cfg.color(j); // }) // .style('fill-opacity', 0.8); // // ///////////////////////////////////////////////////////// // //////// Append invisible circles for tooltip /////////// // ///////////////////////////////////////////////////////// // // //Wrapper for the invisible circles on top // const blobCircleWrapper = g.selectAll('.radarCircleWrapper') // .data(data) // .enter().append('g') // .attr('class', 'radarCircleWrapper'); // // //Append a set of invisible circles on top for the mouseover pop-up // blobCircleWrapper.selectAll('.radarInvisibleCircle') // .data(d => d) // .enter().append('circle') // .attr('class', 'radarInvisibleCircle') // .attr('r', cfg.dotRadius * 1.5) // .attr('cx', (d, i) => rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2)) // .attr('cy', (d, i) => rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2)) // .style('fill', 'none') // .style('pointer-events', 'all') // .on('mouseover', function (d) { // const newX = parseFloat(select(this).attr('cx')) - 10; // const newY = parseFloat(select(this).attr('cy')) - 10; // // tooltip // .attr('x', newX) // .attr('y', newY) // .text(Format(d.value)) // .transition().duration(200) // .style('opacity', 1); // }) // .on('mouseout', () => { // tooltip.transition().duration(200) // .style('opacity', 0); // }); // // //Set up the small tooltip for when you hover over a circle // const tooltip = g.append('text') // .attr('class', 'tooltip') // .style('opacity', 0); // // }//RadarChart
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-layout-row.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, SectionMixin, CcrWriterMixin, ColorSchemaMixin} from '../common/common.js'; import RowMixin from './row-mixin.js'; import Column from './column.js'; import './row.less'; export const Row = React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, SectionMixin, CcrWriterMixin, ColorSchemaMixin, RowMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Layout.Row', classNames: { main: 'uu5-layout-row row', flex: 'uu5-layout-row-flex', flexFull: 'uu5-layout-row-flex-full' }, defaults: { childrenLayoutType: ['column', 'columnCollection', 'float'], childParentsLayoutType: ['root'].concat(['container', 'containerCollection']).concat(['row', 'rowCollection']), parentsLayoutType: ['container', 'rowCollection'] }, errors: { childIsWrong: 'Child %s is not column or column collection.' } }, //@@viewOff:statics //@@viewOn:propTypes //@@viewOff:propTypes //@@viewOn:getDefaultProps //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods expandChild_: function (child, key) { var result = child; if (typeof child.type !== 'function' || !child.type.layoutType || this.getDefault().childrenLayoutType.indexOf(child.type.layoutType) === -1) { if (child.type && this.getDefault().childParentsLayoutType.indexOf(child.type.layoutType) > -1) { this.showError('childIsWrong', [child.type.tagName, this.getDefault().childrenLayoutType.join(', ')], { mixinName: 'UU5_Layout_LayoutMixin', context: { child: { tagName: child.type.tagName, component: child } } }); } else { result = ( <Column parent={this} id={this.getId() + '-column'} key={key} colWidth={child.props.colWidth} > {child} </Column> ); } } return result; }, //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _getMainAttrs: function () { var mainAttrs = this.buildMainAttrs(); switch (this.props.display) { case 'flex': mainAttrs.className += ' ' + this.getClassName().flex; break; case 'flex-full': mainAttrs.className += ' ' + this.getClassName().flexFull; break; } return mainAttrs; },//@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return ( <div {...this._getMainAttrs()}> {this.getHeaderChild()} {this.getFilteredSorterChildren()} {this.getFooterChild()} {this.getDisabledCover()} </div> ); } //@@viewOff:render }); export default Row;
src/web/Line/helpers/subComponents.js
Krizzu/react-progressor
import React from 'react'; import propTypes from 'prop-types'; const absoluteStyle = { position: 'absolute', left: 0, top: 0, }; export const Container = ({ style, children }) => ( <div style={Object.assign(style, { position: 'relative', })} > {children} </div> ); export const Track = ({ style, children }) => ( <div style={Object.assign(style, absoluteStyle)}> {children} </div> ); export const CompletedTrack = ({ style, children, func, time }) => ( <div style={Object.assign(style, absoluteStyle, { transition: `width ${time}ms ${func}`, })} > {children} </div> ); Container.propTypes = { style: propTypes.object, children: propTypes.oneOfType([propTypes.element, propTypes.array]), }; Track.propTypes = { style: propTypes.object, children: propTypes.element, }; CompletedTrack.propTypes = { style: propTypes.object, children: propTypes.element, func: propTypes.string, time: propTypes.number, };
app/components/meal_list.js
therealaldo/MacroManagement
'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, ListView, TouchableOpacity } from 'react-native'; import api from '../utils/api'; import Icon from 'react-native-vector-icons/Ionicons'; export default class MealList extends React.Component { constructor(props) { super(props); this.ds = new ListView.DataSource({ rowHasChanged: (row1, row2) => row !== row2 }); } handleAddMeal(selectedDate, mealType, userId, meal) { api.getRecipeInfo(meal.id) .then((response) => { let calories = Math.floor(response.nutrition.nutrients[0].amount); this.props.addMeal(selectedDate, mealType, userId, meal, calories); }) .catch((err) => { this.props.dispatch(this.props.addMealFailure(err)); }) } renderRow(mealItem) { let uri = `https://spoonacular.com/recipeImages/${ mealItem.image }`; return ( <View style={ styles.mealContainer }> <Image source={{ uri: uri }} style={ styles.mealImage } /> <View style={ styles.mealTextContainer }> <Text style={ styles.mealTitle } numberOfLines={ 1 }>{ mealItem.title }</Text> <Text style={ styles.mealTime } numberOfLines={ 1 }>{ mealItem.readyInMinutes } min.</Text> </View> <View style={ styles.mealButtonContainer }> <TouchableOpacity onPress={() => this.props.handleRecipeSearch(mealItem.id, mealItem.readyInMinutes)}> <Icon name='ios-more' size={ 30 } color='#999' /> </TouchableOpacity> <TouchableOpacity onPress={() => this.handleAddMeal(this.props.selectedDate, this.props.mealType, this.props.userId, mealItem)}> <Icon name='md-add' size={ 30 } color='#999' /> </TouchableOpacity> </View> </View> ) } render() { return ( <View style={ styles.container }> <ListView dataSource={ this.ds.cloneWithRows(this.props.data) } renderRow={ this.renderRow.bind(this) } enableEmptySections={ true } /> </View> ) } }; const styles = StyleSheet.create({ container: { flex: 1, }, mealContainer: { height: 90, flexDirection: 'row', backgroundColor: '#e9e9e9', borderRadius: 7, marginBottom: 10, padding: 10, }, mealImage: { flex: 3, marginRight: 10, }, mealTextContainer: { flexDirection: 'column', justifyContent: 'space-around', flex: 6 }, mealTitle: { fontFamily: 'OpenSans-Semibold', fontSize: 16, marginBottom: 5, color: '#333', }, mealTime: { fontFamily: 'OpenSans-Light', fontSize: 14, color: '#666', }, mealButtonContainer: { justifyContent: 'space-around', flex: 1, alignItems: 'flex-end' } });
src/app-client.js
harrislabel/personal_website
"use strict"; import React from 'react'; import ReactDOM from 'react-dom'; import AppRoutes from './components/AppRoutes'; window.onload = () => { ReactDOM.render(<AppRoutes/>, document.getElementById('main')); };
src/components/LinkButton.js
carlyleec/cc-react
import React from 'react'; // eslint-disable-line import { Link } from 'react-router'; import styled from 'styled-components'; const LinkButton = styled(Link)` background: #2196F3; font-size: 1em; color: #FFF; width: 80%; border-radius: 4px; padding: 5px; margin: auto; margin-top: 0px; display: block; text-decoration: none; text-align: center; box-shadow: 0 6px 10px 0 rgba(0,0,0,0.14), 0 1px 18px 0 rgba(0,0,0,0.12), 0 3px 5px -1px rgba(0,0,0,0.3); @media (min-width: 480px) { margin-top: 20px; padding: 10px; font-size: 1em; } @media (min-width: 768px) { margin-top: 20px; padding: 10px; font-size: 1.5em; } @media (min-width: 992px) { margin-top: 20px; padding: 10px; font-size: 2em; } &:hover{ color: #FFF; background: #1976D2; box-shadow: 0 10px 14px 0 rgba(0,0,0,0.14), 0 1px 18px 0 rgba(0,0,0,0.12), 0 8px 10px -1px rgba(0,0,0,0.3); } `; export default LinkButton;
ajax/libs/zingchart-react/1.0.7/zingchart-react.js
sufuf3/cdnjs
import zingchart from 'zingchart'; import React, { Component } from 'react'; class Core extends Component{ render() { return ( React.createElement("div", {id: this.props.id}) ); } //Called after the render function. componentDidMount(){ zingchart.render({ id : this.props.id, width: (this.props.width || 600), height: (this.props.height || 400), data : this.props.data, theme : (this.props.theme) ? this.props.theme : "light", hideprogresslogo: this.props.hideprogresslogo, output: (this.props.output || 'svg'), }); } //Used to check the values being passed in to avoid unnecessary changes. shouldComponentUpdate(nextProps, nextState){ //Lazy object comparison return !(JSON.stringify(nextProps.data) === JSON.stringify(this.props.data)) ; } componentWillUpdate(nextProps){ zingchart.exec(this.props.id, 'setdata', { data : nextProps.data }); } componentWillUnmount(){ zingchart.exec(this.props.id, 'destroy'); } }; class Line extends Component{ render(){ var myConfig = { type: "line", series : this.props.series }; applyAttrs(this.props, myConfig); return (React.createElement(Core, {id: this.props.id, height: this.props.height, width: this.props.width, data: myConfig, theme: this.props.theme})); } }; class Area extends Component{ render(){ var myConfig = { type: "area", series : this.props.series }; applyAttrs(this.props, myConfig); return (React.createElement(Core, {id: this.props.id, height: this.props.height, width: this.props.width, data: myConfig, theme: this.props.theme})); } }; class Bar extends Component{ render(){ var myConfig = { type: "bar", series : this.props.series }; applyAttrs(this.props, myConfig); return (React.createElement(Core, {id: this.props.id, height: this.props.height, width: this.props.width, data: myConfig, theme: this.props.theme})); } }; class Scatter extends Component{ render(){ var myConfig = { type: "scatter", series : this.props.series }; applyAttrs(this.props, myConfig); return (React.createElement(Core, {id: this.props.id, height: this.props.height, width: this.props.width, data: myConfig, theme: this.props.theme})); } }; class Pie extends Component{ render(){ var myConfig = { type: "pie", series : this.props.series }; applyAttrs(this.props, myConfig); return (React.createElement(Core, {id: this.props.id, height: this.props.height, width: this.props.width, data: myConfig, theme: this.props.theme})); } }; function applyAttrs(oProps, oConfig){ if(oProps.legend && oProps.legend.toLowerCase() == "true"){ oConfig.plotarea = oConfig.plotarea || {}; oConfig.plotarea.marginRight = "150px"; oConfig.legend = { maxItems : "4", overflow : "page" }; } if(oProps.title){ oConfig.title = { text : oProps.title } } } export { Core as core, Line as line, Area as area, Bar as bar, Pie as pie, Scatter as scatter };
src/parser/shared/modules/items/bfa/raids/crucibleofstorms/FathuulsFloodguards.js
sMteX/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS/index'; import SPELLS from 'common/SPELLS/index'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import ItemHealingDone from 'interface/others/ItemHealingDone'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import BoringItemValueText from 'interface/statistics/components/BoringItemValueText'; import { formatNumber, formatPercentage } from 'common/format'; import { TooltipElement } from 'common/Tooltip'; // Example log: https://www.warcraftlogs.com/reports/Px9pcQwt3rFXjDn7#fight=24&source=186 class FathuulsFloodguards extends Analyzer { damage = 0; healing = 0; overHealing = 0; constructor(...args){ super(...args); this.active = this.selectedCombatant.hasLegs(ITEMS.FATHUULS_FLOODGUARDS.id); if(!this.active){ return; } this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.DROWNING_TIDE_DAMAGE), this._damage); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.DROWNING_TIDE_HEAL), this._heal); } _damage(event){ this.damage += (event.amount || 0) + (event.absorbed || 0); } _heal(event){ this.healing += (event.amount || 0) + (event.absorbed || 0); this.overHealing += event.overheal || 0; } get overhealPercent() { return this.overHealing / (this.healing + this.overHealing); } statistic() { return ( <ItemStatistic size="flexible" > <BoringItemValueText item={ITEMS.FATHUULS_FLOODGUARDS}> <TooltipElement content={`Damage done: ${formatNumber(this.damage)}`}> <ItemDamageDone amount={this.damage} /> </TooltipElement><br /> <TooltipElement content={`Healing done: ${formatNumber(this.healing)} (${formatPercentage(this.overhealPercent)}% OH)`}> <ItemHealingDone amount={this.healing} /> </TooltipElement> </BoringItemValueText> </ItemStatistic> ); } } export default FathuulsFloodguards;
src/index.js
EncontrAR/backoffice
import React from 'react'; import ReactDOM from 'react-dom'; import { LocaleProvider } from 'antd'; import { IntlProvider } from 'react-intl'; import registerServiceWorker from './registerServiceWorker'; import DashApp from './dashApp'; import AppLocale from './languageProvider'; import config, { getCurrentLanguage } from './containers/LanguageSwitcher/config'; const currentAppLocale = AppLocale[getCurrentLanguage(config.defaultLanguage || 'english').locale]; ReactDOM.render( <LocaleProvider locale={currentAppLocale.antd}> <IntlProvider locale={currentAppLocale.locale} messages={currentAppLocale.messages} > <DashApp /> </IntlProvider> </LocaleProvider>, document.getElementById('root') ); // Hot Module Replacement API if (module.hot) { module.hot.accept('./dashApp.js', () => { const NextApp = require('./dashApp').default; ReactDOM.render(<NextApp />, document.getElementById('root')); }); } registerServiceWorker(); export { AppLocale };
modules/NavigationMixin.js
RobertKielty/react-router
import invariant from 'invariant'; import React from 'react'; import { stringifyQuery } from './QueryUtils'; var { func } = React.PropTypes; var NavigationMixin = { propTypes: { stringifyQuery: func }, getDefaultProps() { return { stringifyQuery }; }, createPath(pathname, query) { var { stringifyQuery } = this.props; var queryString; if (query == null || (queryString = stringifyQuery(query)) === '') return pathname; return pathname + (pathname.indexOf('?') === -1 ? '?' : '&') + queryString; }, /** * Returns a string that may safely be used to link to the given * pathname and query. */ createHref(pathname, query) { var path = this.createPath(pathname, query); var { history } = this.props; if (history && history.createHref) return history.createHref(path); return path; }, /** * Pushes a new Location onto the history stack. */ transitionTo(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#transitionTo needs history' ); history.pushState(state, this.createPath(pathname, query)); }, /** * Replaces the current Location on the history stack. */ replaceWith(pathname, query, state=null) { var { history } = this.props; invariant( history, 'Router#replaceWith needs history' ); history.replaceState(state, this.createPath(pathname, query)); }, /** * Navigates forward/backward n entries in the history stack. */ go(n) { var { history } = this.props; invariant( history, 'Router#go needs history' ); history.go(n); }, /** * Navigates back one entry in the history stack. This is identical to * the user clicking the browser's back button. */ goBack() { this.go(-1); }, /** * Navigates forward one entry in the history stack. This is identical to * the user clicking the browser's forward button. */ goForward() { this.go(1); } }; export default NavigationMixin;
src/mount_app.js
yormi/test-them-all
'use strict' import React from 'react' import { scryRenderedComponentsWithType, renderIntoDocument } from 'react-addons-test-utils' import { unmountComponentAtNode, findDOMNode } from 'react-dom' import initializeDom from '~/src/setup/setup_fake_dom' import { wrapLifecycleMethodsWithTryCatch } from '~/src/handler_react_component_lifecycle_error' let mountedApp let router export const getMountedApp = () => mountedApp export const getRouterComponent = () => { const router = getReactRouter() try { const routersFound = scryRenderedComponentsWithType(mountedApp, router) if (routersFound.length !== 1) throw routersFound.length return routersFound[0] } catch (err) { if (typeof err === 'number') { throw new Error(`There is not only one react-router Router component but ${err}.`) } else { throw err } } } const getReactRouter = () => { if (!router) { try { router = require('react-router').StaticRouter } catch (err) { throw new Error('"react-router" must be install in your project. Otherwise, test-them-all routing feature doesn\'t make sense. Make sure you have react-router v4. If you do not want to use the version 4 downgrad test-them-all package to a version below 3.') } } return router } export const mountApp = (RootComponent, props = {}, renderFn = renderIntoDocument) => { wrapLifecycleMethodsWithTryCatch(RootComponent) mountedApp = renderFn(<RootComponent {...props} />) return mountedApp } export const unmountApp = () => { try { if (mountedApp) { unmountComponentAtNode(findDOMNode(mountedApp).parentNode) mountedApp = null } initializeDom() } catch (err) { console.info('Error while cleaning the dom: ', err) } }
src/components/App.js
jainvabhi/PWD
require('./ServiceWorker'); import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Route, Redirect, withRouter } from 'react-router-dom'; import Async from 'react-code-splitting'; import Login from './Auth/Login'; import ChatBot from './Chatbot'; import PatientModal from './PatientModal'; import { getPatient, getPhiDetail, showPatientModal, hidePatientModal, } from '../actions/BlockChain'; const Home = () => <Async load={import('./Home')} />; const App = ({ user, getPatient, getPhiDetail, showPatientModal, hidePatientModal, }) => <div> {user.token ? <Route path="/" component={Home} /> : <Redirect to="/login" />} <Route path="/login" component={Login} /> {user.token ? <ChatBot user={user} showPatientModal={showPatientModal} getPhiDetail={e => getPhiDetail(e)} getPatient={e => getPatient(e)} /> : null} {user.token && user.showPatientModal ? <PatientModal user={user} hidePatientModal={hidePatientModal} /> : null} </div>; App.propTypes = { user: PropTypes.shape({}).isRequired, getPatient: PropTypes.func.isRequired, getPhiDetail: PropTypes.func.isRequired, showPatientModal: PropTypes.func.isRequired, hidePatientModal: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ user: state.user }); export default withRouter( connect(mapStateToProps, { getPatient, getPhiDetail, showPatientModal, hidePatientModal, })(App), );
src/js/components/LeftPanel.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import selectn from 'selectn'; import User from '../components/User'; import AuthenticatedComponent from '../components/AuthenticatedComponent'; import translate from '../i18n/Translate'; import connectToStores from '../utils/connectToStores'; import StatsStore from '../stores/StatsStore'; import LoginActionCreators from '../actions/LoginActionCreators'; import Framework7Service from '../services/Framework7Service'; import ChatThreadStore from '../stores/ChatThreadStore'; import UserStore from '../stores/UserStore'; import ProfileStore from '../stores/ProfileStore'; function getState(props) { const stats = StatsStore.stats; const interests = selectn('numberOfContentLikes', stats) || 0; const unreadCount = ChatThreadStore.getUnreadCount() || 0; const profile = ProfileStore.get(props.user.slug); return { interests, unreadCount, profile }; } @AuthenticatedComponent @translate('LeftPanel') @connectToStores([UserStore, StatsStore, ChatThreadStore], getState) export default class LeftPanel extends Component { static contextTypes = { router: PropTypes.object.isRequired }; static propTypes = { // Injected by @AuthenticatedComponent user : PropTypes.object, userLoggedIn: PropTypes.bool, // Injected by @translate: strings : PropTypes.object, // Injected by @connectToStores: interests : PropTypes.number, unreadCount : PropTypes.number }; constructor(props) { super(props); this.handleGoClickThreads = this.handleGoClickThreads.bind(this); this.handleGoClickProfile = this.handleGoClickProfile.bind(this); this.handleGoClickConversations = this.handleGoClickConversations.bind(this); this.handleGoClickSocialNetworks = this.handleGoClickSocialNetworks.bind(this); this.handleGoClickInterests = this.handleGoClickInterests.bind(this); this.handleClickMore = this.handleClickMore.bind(this); this.handleClickSettings = this.handleClickSettings.bind(this); this.handleGoClickInvitations = this.handleGoClickInvitations.bind(this); this.handleGoClickGroups = this.handleGoClickGroups.bind(this); this.pushRoute = this.pushRoute.bind(this); this.logout = this.logout.bind(this); this.state = { moreActive: null }; } componentDidMount() { Framework7Service.$$()('.panel-left').on('closed', () => { this.setState({ moreActive: false }); }); } handleGoClickThreads() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/discover'); }); } handleGoClickProfile() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute(`/p/${this.props.user.slug}`); }); } handleGoClickConversations() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/conversations'); }); } handleGoClickSocialNetworks() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/social-networks'); }); } handleGoClickInterests() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/interests'); }); } handleClickMore() { this.setState({ moreActive: !this.state.moreActive }); } handleClickSettings() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/settings'); }); } handleGoClickInvitations() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/invitations'); }); } handleGoClickGroups() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { this.pushRoute('/badges'); }); } pushRoute(route) { setTimeout(() => { this.context.router.push(route) }, 0); } logout() { Framework7Service.nekunoApp().closePanel(); Framework7Service.$$()('.panel-left').once('closed', () => { setTimeout(() => LoginActionCreators.logoutUser(), 0); }); } render() { const {userLoggedIn, strings, interests, unreadCount} = this.props; const {moreActive} = this.state; return ( <div className="LeftPanel"> <div className="panel-overlay"></div> <div className="panel panel-left panel-reveal"> <div className="content-block top-menu"> <a className="close-panel"> <span className="icon-left-arrow"/> </a> </div> { userLoggedIn ? <User {...this.props} onClick={this.handleGoClickProfile}/> : '' } { userLoggedIn && !moreActive ? <div className="user-interests"> <a href="javascript:void(0)" onClick={this.handleGoClickInterests}> <div className="number"> {interests} </div> <div className="label"> {strings.interests} </div> </a> </div> : null } { userLoggedIn && !moreActive ? <div className="content-block menu"> <a href="javascript:void(0)" onClick={this.handleGoClickThreads}> <span className="icon-search"></span>&nbsp;&nbsp;{strings.threads} </a> {/*<a href="javascript:void(0)" onClick={this.handleGoClickProfile}> {strings.myProfile} </a>*/} <a href="javascript:void(0)" onClick={this.handleGoClickConversations}> <span className="icon-commenting"></span>&nbsp;&nbsp;{strings.conversations} {unreadCount ? <span className="unread-messages-count"> <span className="unread-messages-count-text">{unreadCount}</span> </span> : ''} </a> <a href="javascript:void(0)" onClick={this.handleGoClickGroups}> <span className="icon-puzzle-piece"></span>&nbsp;&nbsp;{strings.groups} </a> <a href="javascript:void(0)" onClick={this.handleClickMore}> <span className="icon-fa-plus"></span>&nbsp;&nbsp;{strings.more} </a> </div> : moreActive ? <div className="content-block menu"> <a href="javascript:void(0)" onClick={this.handleClickMore} style={{fontWeight: 'bold'}}> <span className="icon-left-arrow"></span>&nbsp;&nbsp;{strings.less} </a> <a href="javascript:void(0)" onClick={this.handleGoClickProfile}> <span className="icon-person"></span>&nbsp;&nbsp;{strings.myProfile} </a> <a href="javascript:void(0)" onClick={this.handleGoClickSocialNetworks}> <span className="icon-plug"></span>&nbsp;&nbsp;{strings.socialNetworks} </a> <a href="javascript:void(0)" onClick={this.handleClickSettings}> <span className="icon-preferences"></span>&nbsp;&nbsp;{strings.settings} </a> {/*<Link to="/invitations" onClick={this.handleGoClickInvitations} onlyActiveOnIndex={false}>*/} {/*{strings.invitations}*/} {/*</Link>*/} <a href="javascript:void(0)" onClick={this.logout}> <span className="icon-sign-out"></span>&nbsp;&nbsp;{strings.logout} </a> </div> : '' } </div> </div> ); } } LeftPanel.defaultProps = { strings: { interests : 'Interests', threads : 'Discover', groups : 'Badges', myProfile : 'Profile', conversations : 'Messages', socialNetworks: 'My social networks', more : 'More', less : 'Less', settings : 'Settings', invitations : 'Invitations', logout : 'Logout' } };
renderer/components/Icon/AngleLeft.js
LN-Zap/zap-desktop
import React from 'react' const SvgAngleLeft = props => ( <svg height="1em" viewBox="8.59 6 7.41 12" width="1em" {...props}> <path d="M14.59 18L16 16.59 11.42 12 16 7.41 14.59 6l-6 6z" fill="currentColor" /> </svg> ) export default SvgAngleLeft
src/svg-icons/av/repeat-one.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRepeatOne = (props) => ( <SvgIcon {...props}> <path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z"/> </SvgIcon> ); AvRepeatOne = pure(AvRepeatOne); AvRepeatOne.displayName = 'AvRepeatOne'; AvRepeatOne.muiName = 'SvgIcon'; export default AvRepeatOne;
src/svg-icons/av/subscriptions.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSubscriptions = (props) => ( <SvgIcon {...props}> <path d="M20 8H4V6h16v2zm-2-6H6v2h12V2zm4 10v8c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2v-8c0-1.1.9-2 2-2h16c1.1 0 2 .9 2 2zm-6 4l-6-3.27v6.53L16 16z"/> </SvgIcon> ); AvSubscriptions = pure(AvSubscriptions); AvSubscriptions.displayName = 'AvSubscriptions'; export default AvSubscriptions;
App/Story.js
johnwalley/hacker-news
import React from 'react'; import { StyleSheet, Text, TouchableHighlight, View, } from 'react-native'; const styles = StyleSheet.create({ container: { backgroundColor: 'white', paddingLeft: 10, paddingRight: 10, }, title: { fontSize: 18, color: 'black', fontWeight: 'bold', textAlign: 'left', paddingTop: 5, paddingBottom: 5, }, details: { fontSize: 12, color: 'grey', textAlign: 'left', paddingBottom: 5, }, }); export default Story = ({ onPress, title, points, user, timeAgo, commentsCount, read }) => <TouchableHighlight onPress={onPress}> <View style={styles.container}> <Text style={[styles.title, read && { color: 'grey' }]}>{title}</Text> <Text style={styles.details}>{points} points by {user} {timeAgo} | {commentsCount || 0} comments</Text> </View> </TouchableHighlight >
src/Select.js
paulmillr/react-select
/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ import React from 'react'; import ReactDOM from 'react-dom'; import AutosizeInput from 'react-input-autosize'; import classNames from 'classnames'; import defaultArrowRenderer from './utils/defaultArrowRenderer'; import defaultFilterOptions from './utils/defaultFilterOptions'; import defaultMenuRenderer from './utils/defaultMenuRenderer'; import Async from './Async'; import AsyncCreatable from './AsyncCreatable'; import Creatable from './Creatable'; import Option from './Option'; import Value from './Value'; function stringifyValue (value) { const valueType = typeof value; if (valueType === 'string') { return value; } else if (valueType === 'object') { return JSON.stringify(value); } else if (valueType === 'number' || valueType === 'boolean') { return String(value); } else { return ''; } } const stringOrNode = React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]); let instanceId = 1; const Select = React.createClass({ displayName: 'Select', propTypes: { addLabelText: React.PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input 'aria-label': React.PropTypes.string, // Aria label (for assistive tech) 'aria-labelledby': React.PropTypes.string, // HTML ID of an element that should be used as the label (for assistive tech) arrowRenderer: React.PropTypes.func, // Create drop-down caret element autoBlur: React.PropTypes.bool, // automatically blur the component when an option is selected autofocus: React.PropTypes.bool, // autofocus the component on mount autosize: React.PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: React.PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: React.PropTypes.string, // Message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: React.PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearValueText: stringOrNode, // title for the "clear" control clearable: React.PropTypes.bool, // should it be possible to reset value delimiter: React.PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: React.PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: React.PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: React.PropTypes.func, // method to filter a single option (option, filterString) filterOptions: React.PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: React.PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering inputProps: React.PropTypes.object, // custom attributes for the Input inputRenderer: React.PropTypes.func, // returns a custom input component instanceId: React.PropTypes.string, // set the components instanceId isLoading: React.PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: React.PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: React.PropTypes.string, // path of the label value in option objects matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: React.PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: React.PropTypes.object, // optional style to apply to the menu container menuRenderer: React.PropTypes.func, // renders a custom menu with options menuStyle: React.PropTypes.object, // optional style to apply to the menu multi: React.PropTypes.bool, // multi-value input name: React.PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: React.PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: React.PropTypes.bool, // whether input is cleared on blur onChange: React.PropTypes.func, // onChange handler: function (newValue) {} onClose: React.PropTypes.func, // fires when the menu is closed onCloseResetsInput: React.PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: React.PropTypes.func, // onFocus handler: function (event) {} onInputChange: React.PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: React.PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: React.PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: React.PropTypes.func, // fires when the menu is opened onValueClick: React.PropTypes.func, // onClick handler for value labels: function (value, event) {} openAfterFocus: React.PropTypes.bool, // boolean to enable opening dropdown when focused openOnFocus: React.PropTypes.bool, // always open options menu on focus optionClassName: React.PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: React.PropTypes.func, // option component to render in dropdown optionRenderer: React.PropTypes.func, // optionRenderer: function (option) {} options: React.PropTypes.array, // array of options pageSize: React.PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value required: React.PropTypes.bool, // applies HTML5 required attribute when needed resetValue: React.PropTypes.any, // value to use when you clear the control scrollMenuIntoView: React.PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: React.PropTypes.bool, // whether to enable searching feature or not simpleValue: React.PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: React.PropTypes.object, // optional style to apply to the control tabIndex: React.PropTypes.string, // optional tab index of the control tabSelectsValue: React.PropTypes.bool, // whether to treat tabbing out while focused to be value selection value: React.PropTypes.any, // initial field value valueComponent: React.PropTypes.func, // value component to render valueKey: React.PropTypes.string, // path of the label value in option objects valueRenderer: React.PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: React.PropTypes.object, // optional style to apply to the component wrapper }, statics: { Async, AsyncCreatable, Creatable }, getDefaultProps () { return { addLabelText: 'Add "{label}"?', arrowRenderer: defaultArrowRenderer, autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearValueText: 'Clear value', delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: defaultFilterOptions, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: defaultMenuRenderer, multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, openAfterFocus: false, optionComponent: Option, pageSize: 5, placeholder: 'Select...', required: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, valueComponent: Value, valueKey: 'value', }; }, getInitialState () { return { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false, }; }, componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; const valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: this.handleRequired(valueArray[0], this.props.multi), }); } }, componentDidMount () { if (this.props.autofocus) { this.focus(); } }, componentWillReceiveProps(nextProps) { const valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: this.handleRequired(valueArray[0], nextProps.multi), }); } }, componentWillUpdate (nextProps, nextState) { if (nextState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(nextState.isOpen); const handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose; handler && handler(); } }, componentDidUpdate (prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { let focusedOptionNode = ReactDOM.findDOMNode(this.focused); let menuNode = ReactDOM.findDOMNode(this.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = ReactDOM.findDOMNode(this.focused); var menuDOM = ReactDOM.findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = (focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight); } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } }, componentWillUnmount() { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('ontouchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } }, toggleTouchOutsideEvent(enabled) { if (enabled) { if (!document.addEventListener && document.attachEvent) { document.attachEvent('ontouchstart', this.handleTouchOutside); } else { document.addEventListener('touchstart', this.handleTouchOutside); } } else { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('ontouchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } } }, handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } }, focus () { if (!this.input) return; this.input.focus(); if (this.props.openAfterFocus) { this.setState({ isOpen: true, }); } }, blurInput() { if (!this.input) return; this.input.blur(); }, handleTouchMove (event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart (event) { // Set a flag that the view is not being dragged this.dragging = false; }, handleTouchEnd (event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if(this.dragging) return; // Fire the mouse events this.handleMouseDown(event); }, handleTouchEndClearValue (event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if(this.dragging) return; // Clear the value this.clearValue(event); }, handleMouseDown (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } if (event.target.tagName === 'INPUT') { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen, }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); let input = this.input; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false, }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, handleMouseDownOnMenu (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); }, closeMenu () { if(this.props.onCloseResetsInput) { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '' }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: this.state.inputValue }); } this.hasScrolledToOption = false; }, handleInputFocus (event) { if (this.props.disabled) return; var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur (event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false, }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = ''; } this.setState(onBlurredState); }, handleInputChange (event) { let newInputValue = event.target.value; if (this.state.inputValue !== event.target.value && this.props.onInputChange) { let nextState = this.props.onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && typeof nextState !== 'object') { newInputValue = '' + nextState; } } this.setState({ isOpen: true, isPseudoFocused: false, inputValue: newInputValue }); }, handleKeyDown (event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { return; } this.selectFocusedOption(); return; case 13: // enter if (!this.state.isOpen) return; event.stopPropagation(); this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 33: // page up this.focusPageUpOption(); break; case 34: // page down this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { return; } this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { return; } this.focusStartOption(); break; default: return; } event.preventDefault(); }, handleValueClick (option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll (event) { if (!this.props.onMenuScrollToBottom) return; let { target } = event; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, handleRequired (value, multi) { if (!value) return true; return (multi ? value.length === 0 : Object.keys(value).length === 0); }, getOptionLabel (op) { return op[this.props.labelKey]; }, /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ getValueArray (value, nextProps) { /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ const props = typeof nextProps === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') value = value.split(props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(value => this.expandValue(value, props)).filter(i => i); } var expandedValue = this.expandValue(value, props); return expandedValue ? [expandedValue] : []; }, /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ expandValue (value, props) { const valueType = typeof value; if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; let { options, valueKey } = props; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue (value) { if (this.props.autoBlur){ this.blurInput(); } if (!this.props.onChange) return; if (this.props.required) { const required = this.handleRequired(value, this.props.multi); this.setState({ required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(i => i[this.props.valueKey]).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue (value) { //NOTE: update value in the callback to make sure the input value is empty so that there are no styling issues (Chrome had issue otherwise) this.hasScrolledToOption = false; if (this.props.multi) { this.setState({ inputValue: '', focusedIndex: null }, () => { this.addValue(value); }); } else { this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused, }, () => { this.setValue(value); }); } }, addValue (value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.concat(value)); }, popValue () { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length-1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue (value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(i => i !== value)); this.focus(); }, clearValue (event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ isOpen: false, inputValue: '', }, this.focus); }, getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } }, focusOption (option) { this.setState({ focusedOption: option }); }, focusNextOption () { this.focusAdjacentOption('next'); }, focusPreviousOption () { this.focusAdjacentOption('previous'); }, focusPageUpOption () { this.focusAdjacentOption('page_up'); }, focusPageDownOption () { this.focusAdjacentOption('page_down'); }, focusStartOption () { this.focusAdjacentOption('start'); }, focusEndOption () { this.focusAdjacentOption('end'); }, focusAdjacentOption (dir) { var options = this._visibleOptions .map((option, index) => ({ option, index })) .filter(option => !option.option.disabled); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1].option }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1 ) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if ( potentialIndex < 0 ) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var potentialIndex = focusedIndex + this.props.pageSize; if ( potentialIndex > options.length - 1 ) { focusedIndex = options.length - 1; } else { focusedIndex = potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); }, getFocusedOption () { return this._focusedOption; }, getInputValue () { return this.state.inputValue; }, selectFocusedOption () { if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading () { if (!this.props.isLoading) return; return ( <span className="Select-loading-zone" aria-hidden="true"> <span className="Select-loading" /> </span> ); }, renderValue (valueArray, isOpen) { let renderLabel = this.props.valueRenderer || this.getOptionLabel; let ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? <div className="Select-placeholder">{this.props.placeholder}</div> : null; } let onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map((value, i) => { return ( <ValueComponent id={this._instancePrefix + '-value-' + i} instancePrefix={this._instancePrefix} disabled={this.props.disabled || value.clearableValue === false} key={`value-${i}-${value[this.props.valueKey]}`} onClick={onClick} onRemove={this.removeValue} value={value} > {renderLabel(value, i)} <span className="Select-aria-only">&nbsp;</span> </ValueComponent> ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return ( <ValueComponent id={this._instancePrefix + '-value-item'} disabled={this.props.disabled} instancePrefix={this._instancePrefix} onClick={onClick} value={valueArray[0]} > {renderLabel(valueArray[0])} </ValueComponent> ); } }, renderInput (valueArray, focusedOptionIndex) { if (this.props.inputRenderer) { return this.props.inputRenderer(); } else { var className = classNames('Select-input', this.props.inputProps.className); const isOpen = !!this.state.isOpen; const ariaOwns = classNames({ [this._instancePrefix + '-list']: isOpen, [this._instancePrefix + '-backspace-remove-message']: this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue }); // TODO: Check how this project includes Object.assign() const inputProps = Object.assign({}, this.props.inputProps, { role: 'combobox', 'aria-expanded': '' + isOpen, 'aria-owns': ariaOwns, 'aria-haspopup': '' + isOpen, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: ref => this.input = ref, required: this.state.required, value: this.state.inputValue }); if (this.props.disabled || !this.props.searchable) { const { inputClassName, ...divProps } = this.props.inputProps; return ( <div {...divProps} role="combobox" aria-expanded={isOpen} aria-owns={isOpen ? this._instancePrefix + '-list' : this._instancePrefix + '-value'} aria-activedescendant={isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value'} className={className} tabIndex={this.props.tabIndex || 0} onBlur={this.handleInputBlur} onFocus={this.handleInputFocus} ref={ref => this.input = ref} aria-readonly={'' + !!this.props.disabled} style={{ border: 0, width: 1, display:'inline-block' }}/> ); } if (this.props.autosize) { return ( <AutosizeInput {...inputProps} minWidth="5" /> ); } return ( <div className={ className }> <input {...inputProps} /> </div> ); } }, renderClear () { if (!this.props.clearable || (!this.props.value || this.props.value === 0) || (this.props.multi && !this.props.value.length) || this.props.disabled || this.props.isLoading) return; return ( <span className="Select-clear-zone" title={this.props.multi ? this.props.clearAllText : this.props.clearValueText} aria-label={this.props.multi ? this.props.clearAllText : this.props.clearValueText} onMouseDown={this.clearValue} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEndClearValue} > <span className="Select-clear" dangerouslySetInnerHTML={{ __html: '&times;' }} /> </span> ); }, renderArrow () { const onMouseDown = this.handleMouseDownOnArrow; const arrow = this.props.arrowRenderer({ onMouseDown }); return ( <span className="Select-arrow-zone" onMouseDown={onMouseDown} > {arrow} </span> ); }, filterOptions (excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute const filterOptions = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : defaultFilterOptions; return filterOptions( options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, valueKey: this.props.valueKey, } ); } else { return options; } }, onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } }, renderMenu (options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption, focusOption: this.focusOption, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options, selectValue: this.selectValue, valueArray, valueKey: this.props.valueKey, onOptionRef: this.onOptionRef, }); } else if (this.props.noResultsText) { return ( <div className="Select-noresults"> {this.props.noResultsText} </div> ); } else { return null; } }, renderHiddenField (valueArray) { if (!this.props.name) return; if (this.props.joinValues) { let value = valueArray.map(i => stringifyValue(i[this.props.valueKey])).join(this.props.delimiter); return ( <input type="hidden" ref={ref => this.value = ref} name={this.props.name} value={value} disabled={this.props.disabled} /> ); } return valueArray.map((item, index) => ( <input key={'hidden.' + index} type="hidden" ref={'value' + index} name={this.props.name} value={stringifyValue(item[this.props.valueKey])} disabled={this.props.disabled} /> )); }, getFocusableOptionIndex (selectedOption) { var options = this._visibleOptions; if (!options.length) return null; let focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { const focusedOptionIndex = options.indexOf(focusedOption); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; }, renderOuter (options, valueArray, focusedOption) { let menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return ( <div ref={ref => this.menuContainer = ref} className="Select-menu-outer" style={this.props.menuContainerStyle}> <div ref={ref => this.menu = ref} role="listbox" className="Select-menu" id={this._instancePrefix + '-list'} style={this.props.menuStyle} onScroll={this.handleMenuScroll} onMouseDown={this.handleMouseDownOnMenu}> {menu} </div> </div> ); }, render () { let valueArray = this.getValueArray(this.props.value); let options = this._visibleOptions = this.filterOptions(this.props.multi ? this.getValueArray(this.props.value) : null); let isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; const focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); let focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } let className = classNames('Select', this.props.className, { 'Select--multi': this.props.multi, 'Select--single': !this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length, }); let removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = ( <span id={this._instancePrefix + '-backspace-remove-message'} className="Select-aria-only" aria-live="assertive"> {this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey])} </span> ); } return ( <div ref={ref => this.wrapper = ref} className={className} style={this.props.wrapperStyle}> {this.renderHiddenField(valueArray)} <div ref={ref => this.control = ref} className="Select-control" style={this.props.style} onKeyDown={this.handleKeyDown} onMouseDown={this.handleMouseDown} onTouchEnd={this.handleTouchEnd} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} > <span className="Select-multi-value-wrapper" id={this._instancePrefix + '-value'}> {this.renderValue(valueArray, isOpen)} {this.renderInput(valueArray, focusedOptionIndex)} </span> {removeMessage} {this.renderLoading()} {this.renderClear()} {this.renderArrow()} </div> {isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null} </div> ); } }); export default Select;
app/javascript/mastodon/features/community_timeline/components/column_settings.js
res-ac/mstdn.res.ac
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; @injectIntl export default class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media Only' />} /> </div> </div> ); } }
src/components/views/dialogs/SessionRestoreErrorDialog.js
aperezdc/matrix-react-sdk
/* Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import sdk from '../../../index'; import SdkConfig from '../../../SdkConfig'; import Modal from '../../../Modal'; import { _t } from '../../../languageHandler'; export default React.createClass({ displayName: 'SessionRestoreErrorDialog', propTypes: { error: PropTypes.string.isRequired, onFinished: PropTypes.func.isRequired, }, _sendBugReport: function() { const BugReportDialog = sdk.getComponent("dialogs.BugReportDialog"); Modal.createTrackedDialog('Session Restore Error', 'Send Bug Report Dialog', BugReportDialog, {}); }, _onClearStorageClick: function() { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); Modal.createTrackedDialog('Session Restore Confirm Logout', '', QuestionDialog, { title: _t("Sign out"), description: <div>{ _t("Log out and remove encryption keys?") }</div>, button: _t("Sign out"), danger: true, onFinished: this.props.onFinished, }); }, _onRefreshClick: function() { // Is this likely to help? Probably not, but giving only one button // that clears your storage seems awful. window.location.reload(true); }, render: function() { const BaseDialog = sdk.getComponent('views.dialogs.BaseDialog'); const DialogButtons = sdk.getComponent('views.elements.DialogButtons'); const clearStorageButton = ( <button onClick={this._onClearStorageClick} className="danger"> { _t("Clear Storage and Sign Out") } </button> ); let dialogButtons; if (SdkConfig.get().bug_report_endpoint_url) { dialogButtons = <DialogButtons primaryButton={_t("Send Logs")} onPrimaryButtonClick={this._sendBugReport} focus={true} hasCancel={false} > { clearStorageButton } </DialogButtons>; } else { dialogButtons = <DialogButtons primaryButton={_t("Refresh")} onPrimaryButtonClick={this._onRefreshClick} focus={true} hasCancel={false} > { clearStorageButton } </DialogButtons>; } return ( <BaseDialog className="mx_ErrorDialog" onFinished={this.props.onFinished} title={_t('Unable to restore session')} contentId='mx_Dialog_content' hasCancel={false} > <div className="mx_Dialog_content" id='mx_Dialog_content'> <p>{ _t("We encountered an error trying to restore your previous session.") }</p> <p>{ _t( "If you have previously used a more recent version of Riot, your session " + "may be incompatible with this version. Close this window and return " + "to the more recent version.", ) }</p> <p>{ _t( "Clearing your browser's storage may fix the problem, but will sign you " + "out and cause any encrypted chat history to become unreadable.", ) }</p> </div> { dialogButtons } </BaseDialog> ); }, });
src/content/work/assets/StickFigureSoiree/index.js
jmikrut/keen-2017
import React from 'react'; import VerticalSplit from '../../../../components/Layout/VerticalSplit'; import ContentBlock from '../../../../components/Layout/ContentBlock'; import ImageBlock from '../../../../components/Layout/ImageBlock'; import Gutter from '../../../../components/Layout/Gutter'; import ProjectCTA from '../../../../components/Elements/ProjectCTA'; import IFrame from '../../../../components/Elements/IFrame'; import randomArray from '../../../../utilities/randomNumberArray'; import './StickFigureSoiree.css'; import bg from './images/bg.jpg'; import sketch from './images/sketch.jpg'; import sketchB from './images/sketch-b.jpg'; import asset1 from './images/ph-asset-1.svg'; import asset2 from './images/ph-asset-2.svg'; import asset3 from './images/ph-asset-3.svg'; import hospitalSVG from './images/hospital.svg'; const StickFigureSoiree = (props) => { let animateOrder = randomArray(3); return ( <article className="stick-figure-soiree"> <Gutter data-animate={animateOrder[0]} primaryColor={props.secondaryColor} secondaryColor={props.primaryColor}> <VerticalSplit primaryColor={props.primaryColor} secondaryColor={props.secondaryColor} content={ <ContentBlock className="ph-intro"> <div className="row"> <h4>A creative approach to healthcare</h4> <p>We work with Priority Health on a variety of projects, but none as vigorously as their video library. We use motion graphics, illustration, and video to help explain plan types and educate plan members.</p> </div> </ContentBlock> } split={ <IFrame title="Priority Health MedNow Animation" src="https://www.youtube.com/embed/y8vT8enGNfw?rel=0&amp;showinfo=0" /> }/> <ContentBlock className="ph-sketches-intro"> <h4>Start from scratch</h4> <div className="row"> <p>Every piece we work on with Priority Health starts with a script - it's like the skeleton of the project. We spend a lot of time analyzing all aspects of the script to understand what the client is trying to convey with the video.</p> <p>Once we have a thorough understanding of the script, a storyboard is sketched by hand and later digitized before being sent to the client for approval to proceed.</p> </div> </ContentBlock> <div className="sketch-images"> <img src={sketch} alt="Priority Health Sketches" /> <img src={sketchB} alt="Priority Health Storyboarding"/> </div> <ContentBlock className="ph-assets-intro"> <div className="row"> <h4>Branded Assets</h4> <p>Once the storyboard is approved, assets are created and exported. Each asset is a custom illustrated piece designed to fit within the brand guides and style. This ensures cohesiveness throughout the entire video library.</p> </div> </ContentBlock> <ul className="ph-svgs"> <li> <img alt="Priority Health Doctor Asset" src={asset1} /> </li> <li> <img alt="Priority Health Safe Asset" src={asset2} /> </li> <li> <img alt="Priority Health Piggy Bank SVG Asset" src={asset3} /> </li> </ul> <ImageBlock className="ph-hospital-svg"> <img alt="Priority Health Piggy Hospital SVG Asset" src={hospitalSVG} /> </ImageBlock> <ContentBlock className="ph-working-intro"> <h4>Now for the real fun</h4> <div className="row"> <p>After we've got a complete library of assets prepared, we import everything into our animation software. We use Adobe After Effects and Premier for motion graphics and video edits, and we rig characters in Rubberhose. We make a specific effort to pour nuance into everything that we animate.</p> <p>We take our time and work in secondary animations like jiggles, bounces, and flickers to increase visual interest even more. A professional voiceover is recorded from the script and is then laid over a specially sourced music track for each project.</p> </div> </ContentBlock> <ImageBlock className="ph-working"> <img src={bg} alt="Working on Priority Health Animations" /> </ImageBlock> </Gutter> <ProjectCTA className="motion" /> </article> ) } export default StickFigureSoiree;
stories/components/menu.stories.js
LN-Zap/zap-desktop
import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { Menu } from 'components/UI' const items = [ { id: 'item1', title: 'Item 1', onClick: action }, { id: 'item2', title: 'Item 2', onClick: action }, { id: 'item3', title: 'Item 3', onClick: action }, ] storiesOf('Components', module).addWithChapters('Menu', { subtitle: 'For linking to things', info: `The Menu component is used to present lists of links.`, chapters: [ { sections: [ { sectionFn: () => <Menu items={items} />, }, ], }, ], })
src/components/viewer3d/viewer3d.js
dearkaran/react-planner
"use strict"; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import * as Three from 'three'; import {parseData, updateScene} from './scene-creator'; import {disposeScene} from './three-memory-cleaner'; import OrbitControls from './libs/orbit-controls'; import diff from 'immutablediff'; import * as SharedStyle from '../../shared-style'; export default class Scene3DViewer extends React.Component { constructor(props) { super(props); this.lastMousePosition = {}; this.width = props.width; this.height = props.height; this.stopRendering = false; this.renderer = window.__threeRenderer || new Three.WebGLRenderer({preserveDrawingBuffer: true}); window.__threeRenderer = this.renderer; } componentDidMount() { let actions = { areaActions: this.context.areaActions, holesActions: this.context.holesActions, itemsActions: this.context.itemsActions, linesActions: this.context.linesActions, projectActions: this.context.projectActions }; let {state} = this.props; let data = state.scene; let canvasWrapper = ReactDOM.findDOMNode(this.refs.canvasWrapper); let scene3D = new Three.Scene(); //RENDERER this.renderer.setClearColor(new Three.Color(SharedStyle.COLORS.white)); this.renderer.setSize(this.width, this.height); // LOAD DATA let planData = parseData(data, actions, this.context.catalog); scene3D.add(planData.plan); scene3D.add(planData.grid); let aspectRatio = this.width / this.height; let camera = new Three.PerspectiveCamera(45, aspectRatio, 1, 300000); scene3D.add(camera); // Set position for the camera let cameraPositionX = -(planData.boundingBox.max.x - planData.boundingBox.min.x) / 2; let cameraPositionY = (planData.boundingBox.max.y - planData.boundingBox.min.y) / 2 * 10; let cameraPositionZ = (planData.boundingBox.max.z - planData.boundingBox.min.z) / 2; camera.position.set(cameraPositionX, cameraPositionY, cameraPositionZ); camera.up = new Three.Vector3(0, 1, 0); // HELPER AXIS // let axisHelper = new Three.AxisHelper(100); // scene3D.add(axisHelper); // LIGHT let light = new Three.AmbientLight(0xafafaf); // soft white light scene3D.add(light); // Add another light let spotLight1 = new Three.SpotLight(SharedStyle.COLORS.white, 0.30); spotLight1.position.set(cameraPositionX, cameraPositionY, cameraPositionZ); scene3D.add(spotLight1); // OBJECT PICKING let toIntersect = [planData.plan]; let mouse = new Three.Vector2(); let raycaster = new Three.Raycaster(); this.mouseDownEvent = (event) => { this.lastMousePosition.x = event.offsetX / this.width * 2 - 1; this.lastMousePosition.y = -event.offsetY / this.height * 2 + 1; }; this.mouseUpEvent = (event) => { event.preventDefault(); mouse.x = (event.offsetX / this.width) * 2 - 1; mouse.y = -(event.offsetY / this.height) * 2 + 1; if (Math.abs(mouse.x - this.lastMousePosition.x) <= 0.02 && Math.abs(mouse.y - this.lastMousePosition.y) <= 0.02) { raycaster.setFromCamera(mouse, camera); let intersects = raycaster.intersectObjects(toIntersect, true); if (intersects.length > 0 && !(isNaN(intersects[0].distance))) { intersects[0].object.interact && intersects[0].object.interact(); } else { this.context.projectActions.unselectAll(); } } }; this.renderer.domElement.addEventListener('mousedown', this.mouseDownEvent); this.renderer.domElement.addEventListener('mouseup', this.mouseUpEvent); this.renderer.domElement.style.display = 'block'; // add the output of the renderer to the html element canvasWrapper.appendChild(this.renderer.domElement); // create orbit controls let orbitController = new OrbitControls(camera, this.renderer.domElement); let spotLightTarget = new Three.Object3D(); spotLightTarget.position.set(orbitController.target.x, orbitController.target.y, orbitController.target.z); scene3D.add(spotLightTarget); spotLight1.target = spotLightTarget; /************************************/ /********* SCENE EXPORTER ***********/ /************************************/ let exportScene = () => { let convertToBufferGeometry = (geometry) => { console.log("geometry = ", geometry); let bufferGeometry = new Three.BufferGeometry().fromGeometry(geometry); return bufferGeometry; }; scene3D.remove(planData.grid); scene3D.traverse((child) => { console.log(child); if (child instanceof Three.Mesh && !(child.geometry instanceof Three.BufferGeometry)) child.geometry = convertToBufferGeometry(child.geometry); }); let output = scene3D.toJSON(); output = JSON.stringify(output, null, '\t'); output = output.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1'); let name = prompt('insert file name'); name = name.trim() || 'scene'; let blob = new Blob([output], {type: 'text/plain'}); let fileOutputLink = document.createElement('a'); let url = window.URL.createObjectURL(blob); fileOutputLink.setAttribute('download', name); fileOutputLink.href = url; document.body.appendChild(fileOutputLink); fileOutputLink.click(); document.body.removeChild(fileOutputLink); scene3D.add(planData.grid); }; // window.exportScene = exportScene; /************************************/ /************************************/ /********** PLAN EXPORTER ***********/ /************************************/ let exportPlan = () => { let convertToBufferGeometry = (geometry) => { console.log("geometry = ", geometry); return new Three.BufferGeometry().fromGeometry(geometry); }; planData.plan.traverse((child) => { console.log(child); if (child instanceof Three.Mesh && !(child.geometry instanceof Three.BufferGeometry)) child.geometry = convertToBufferGeometry(child.geometry); }); let output = planData.plan.toJSON(); output = JSON.stringify(output, null, '\t'); output = output.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1'); let name = prompt('insert file name'); name = name.trim() || 'plan'; let blob = new Blob([output], {type: 'text/plain'}); let fileOutputLink = document.createElement('a'); let url = window.URL.createObjectURL(blob); fileOutputLink.setAttribute('download', name); fileOutputLink.href = url; document.body.appendChild(fileOutputLink); fileOutputLink.click(); document.body.removeChild(fileOutputLink); scene3D.add(planData.grid); }; // window.exportPlan = exportPlan; /************************************/ let render = () => { if (!this.stopRendering) { orbitController.update(); spotLight1.position.set(camera.position.x, camera.position.y, camera.position.z); spotLightTarget.position.set(orbitController.target.x, orbitController.target.y, orbitController.target.z); camera.updateMatrix(); camera.updateMatrixWorld(); for (let elemID in planData.sceneGraph.LODs) { planData.sceneGraph.LODs[elemID].update(camera) } this.renderer.render(scene3D, camera); requestAnimationFrame(render); } }; render(); this.orbitControls = orbitController; this.camera = camera; this.scene3D = scene3D; this.planData = planData; } componentWillUnmount() { this.orbitControls.dispose(); this.stopRendering = true; this.renderer.domElement.removeEventListener('mousedown', this.mouseDownEvent); this.renderer.domElement.removeEventListener('mouseup', this.mouseUpEvent); disposeScene(this.scene3D); this.scene3D.remove(this.planData.plan); this.scene3D.remove(this.planData.grid); this.scene3D = null; // this.planData.sceneGraph = null; this.planData = null; } componentWillReceiveProps(nextProps) { let {width, height} = nextProps; let {camera, renderer, scene3D} = this; let actions = { areaActions: this.context.areaActions, holesActions: this.context.holesActions, itemsActions: this.context.itemsActions, linesActions: this.context.linesActions, projectActions: this.context.projectActions }; this.width = width; this.height = height; camera.aspect = width / height; camera.updateProjectionMatrix(); if (nextProps.state.scene !== this.props.state.scene) { let changedValues = diff(this.props.state.scene, nextProps.state.scene); updateScene(this.planData, nextProps.state.scene, this.props.state.scene, changedValues.toJS(), actions, this.context.catalog); } renderer.setSize(width, height); //renderer.render(scene3D, camera); } render() { return React.createElement("div", { ref: "canvasWrapper" }); } } Scene3DViewer.propTypes = { state: PropTypes.object.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired }; Scene3DViewer.contextTypes = { areaActions: PropTypes.object.isRequired, holesActions: PropTypes.object.isRequired, itemsActions: PropTypes.object.isRequired, linesActions: PropTypes.object.isRequired, projectActions: PropTypes.object.isRequired, catalog: PropTypes.object };
tndata_backend/chat/static/react-chat/src/components/websocket.js
izzyalonso/tndata_backend
import React from 'react'; //import ReactDOM from 'react-dom'; /* * Adapted from: * https://github.com/mehmetkose/react-websocket/blob/master/index.jsx */ class Websocket extends React.Component { constructor(props) { super(props); this.send = this.send.bind(this); this.state = { ws: new WebSocket(this.props.url, this.props.protocol), attempts: 1, }; this.lastMessage = ''; } logging(logline) { if (this.props.debug === true) { console.log(logline); } } generateInterval (k) { return Math.min(30, (Math.pow(2, k) - 1)) * 1000; } setupWebsocket() { let websocket = this.state.ws; websocket.onopen = () => { this.logging('Websocket connected'); }; websocket.onmessage = (evt) => { // EXPECTED data format in json: {from: ..., message: ...} this.logging("RECEIVED: " + evt.data) const data = JSON.parse(evt.data); this.props.onMessage(data); }; this.shouldReconnect = this.props.reconnect; websocket.onclose = () => { this.logging('Websocket disconnected'); if (this.shouldReconnect) { let time = this.generateInterval(this.state.attempts); setTimeout(() => { this.setState({attempts: this.state.attempts++}); this.setupWebsocket(); }, time); } } } componentDidMount() { this.setupWebsocket(); } componentWillUnmount() { this.shouldReconnect = false; let websocket = this.state.ws; websocket.close(); } send() { // Only send data if the websocket is open. See: // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Constants if(this.state.ws.readyState === 1) { // This gets run during a render() because the message we want to send // changes on the props. We *can't* call `setState`, here, so we'll // just keep the last-sent message as an attribute on the class. // if(this.props.sendMessage && this.props.sendMessage !== this.lastMessage) { this.state.ws.send(this.props.sendMessage); this.lastMessage = this.props.sendMessage; } // Send read receipt if we have appropriate data. if(this.props.received) { this.state.ws.send(JSON.stringify({ received: this.props.received })); } } } render() { this.send(); return ( <div></div> ); } } Websocket.defaultProps = { debug: false, reconnect: true }; Websocket.propTypes = { url: React.PropTypes.string.isRequired, onMessage: React.PropTypes.func.isRequired, debug: React.PropTypes.bool, reconnect: React.PropTypes.bool, protocol: React.PropTypes.string }; export default Websocket;
app/features/settings/RangeField.js
Kaniwani/KW-Frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Block, Label, Note } from './styles'; const RangeField = ({ input, min, max, step, label, note, display }) => ( <Block> <Label htmlFor={input.name}> <span>{label || input.name}</span> <input id={input.name} type="range" {...input} min={min} max={max} step={step} /> <div>{display(input.value)}</div> </Label> {note && <Note constrain>{note}</Note>} </Block> ); RangeField.propTypes = { input: PropTypes.object.isRequired, min: PropTypes.number.isRequired, max: PropTypes.number.isRequired, step: PropTypes.number.isRequired, label: PropTypes.string.isRequired, note: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), display: PropTypes.func, }; RangeField.defaultProps = { display: (x) => x, note: '', }; export default RangeField;
src/svg-icons/notification/sync.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSync = (props) => ( <SvgIcon {...props}> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/> </SvgIcon> ); NotificationSync = pure(NotificationSync); NotificationSync.displayName = 'NotificationSync'; NotificationSync.muiName = 'SvgIcon'; export default NotificationSync;
docs/src/IntroductionPage.js
dongtong/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
index.ios.js
feedreaderco/app
import React, { Component } from 'react'; import { AppRegistry, Linking, } from 'react-native'; import App from './components/app'; import ShareExtension from './share-extension.ios'; export default class FeedReader extends Component { componentDidMount() { Linking.addEventListener('url', this._handleOpenURL); } componentWillUnmount() { Linking.removeEventListener('url', this._handleOpenURL); } _handleOpenURL(event) { console.log(event.url); } render() { return <App/>; } } AppRegistry.registerComponent('FeedReader', () => FeedReader); AppRegistry.registerComponent('ShareExtension', () => ShareExtension);
pootle/static/js/shared/components/FormValueInput.js
dwaynebailey/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import AutosizeTextarea from './AutosizeTextarea'; const FormValueInput = React.createClass({ propTypes: { handleChange: React.PropTypes.func.isRequired, autosize: React.PropTypes.bool, type: React.PropTypes.string, value: React.PropTypes.string, }, getDefaultProps() { return { autosize: true, }; }, handleChange(e) { this.props.handleChange(e.target.name, e.target.value); }, render() { if (this.props.type === 'textarea') { if (this.props.autosize) { return ( <AutosizeTextarea onChange={this.handleChange} {...this.props} /> ); } return ( <textarea onChange={this.handleChange} {...this.props} /> ); } return <input onChange={this.handleChange} {...this.props} />; }, }); export default FormValueInput;
app/containers/DeckListContainer.js
Ruin0x11/fleet
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Home from '../components/Home'; import DeckList from '../components/DeckList'; import { getDeckList } from '../selectors/port'; function mapStateToProps (state) { if(!state.portData.api_deck_port) { return { decks: [], currentDeck: -1 }; } return { decks: getDeckList(state), currentDeck: 0 }; } const DeckListContainer = React.createClass({ render() { return <DeckList {...this.props} />; } }); export default connect(mapStateToProps)(DeckListContainer);
src/svg-icons/notification/confirmation-number.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
src/modules/Profile/components/ListenAnytime.js
prjctrft/mantenuto
import React from 'react'; import PropTypes from 'prop-types'; const ListenAnytime = (props) => { const styles = require('./ListenAnytime.scss'); return ( <div className={styles.ListenAnytime}> <h2>Listen anytime?</h2> {props.listenAnytime ? <button className={styles.on} onClick={props.toggleListen}>On</button> : <button className={styles.off} onClick={props.toggleListen}>Off</button>} </div> ); } ListenAnytime.propTypes = { toggleListen: PropTypes.func.isRequired, listenAnytime: PropTypes.bool.isRequired }; export default ListenAnytime;
src/components/products/ProductsPage.js
hyoushke/hyo-reactredux-generator
import React from 'react'; import {Link} from 'react-router'; class ProductsPage extends React.Component{ render(){ return ( <div>Products Page Yeah Bah</div> ); } } export default ProductsPage;
packages/icons/src/md/hardware/Laptop.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLaptop(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M40 36h8v4H0v-4h8c-2.2 0-4-1.8-4-4V12c0-2.2 1.8-4 4-4h32c2.2 0 4 1.8 4 4v20c0 2.2-1.8 4-4 4zM8 12v20h32V12H8z" /> </IconBase> ); } export default MdLaptop;
app/containers/users/profile.js
DeividasK/tgoals
import React from 'react' import { Link } from 'react-router' import { connect } from 'react-redux' import { firebaseConnect, helpers } from 'react-redux-firebase' import { ButtonGroup, Button } from 'reactstrap' import { injectIntl } from 'react-intl' import PrimaryGoalsList from 'components/lists/primary-goals-list' import PageHeading from 'components/helper/PageHeading' import Loading from 'components/helper/Loading' import BackButton from 'components/buttons/back' import SimpleList from 'components/lists/simple' import DH from 'utils/DatabaseHelper' import TH from 'utils/TranslationHelper' import { updateUser } from 'actions/FirebaseActions' @connect(({ firebase }) => ({ auth: helpers.pathToJS(firebase, 'auth') })) @firebaseConnect((props) => ([ { path: DH.getUserProfile(props.auth.uid) }, // { path: DH.goals(), queryParams: DH.goalsWithPartner(props.auth.uid), type: 'once' }, ])) @connect(({ firebase }, props) => ({ user: helpers.dataToJS(firebase, DH.getUserProfile(props.auth.uid)), // goalsWatched: helpers.dataToJS(firebase, DH.goals()), })) class ProfileContainer extends React.Component { availableAsPartner (status) { updateUser({ partner: status }) } render () { const { user, goalsWatched, intl: { formatMessage } } = this.props if (user === undefined) { return <Loading /> } return ( <div className="user-detail"> <PageHeading>{ user.displayName }</PageHeading> <img src={ user.avatarUrl } /> <div className="mt-3"> <ButtonGroup> <Button active={ user.partner === true } onClick={ this.availableAsPartner.bind(this, true) }>{ formatMessage(TH.yes) }</Button>{' '} <Button active={ user.partner === undefined || user.partner === false } onClick={ this.availableAsPartner.bind(this, false) }>{ formatMessage(TH.no) }</Button> </ButtonGroup> <span className="ml-3">{ formatMessage(TH.wantToBePartner) }</span> </div> <br /> <BackButton action={ this.props.router.goBack } /> </div> ) } } export default injectIntl(ProfileContainer) // <p>Tikslai, prie kurių aš prisidedu kaip PARTNERIS:</p> // <SimpleList items={ goalsWatched } /> // <p>Noriu būti ekspertu.</p>
src/Parser/Core/Modules/Items/VialOfCeaselessToxins.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS_OTHERS'; import { formatNumber } from 'common/format'; import Module from 'Parser/Core/Module'; class VialOfCeaselessToxins extends Module { damageIncreased = 0; totalCasts = 0; on_initialized() { if (!this.owner.error) { this.active = this.owner.selectedCombatant.hasTrinket(ITEMS.VIAL_OF_CEASELESS_TOXINS.id); } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.CEASELESS_TOXIN.id) { this.totalCasts++; return; } } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.CEASELESS_TOXIN.id) { this.damageIncreased += event.amount; } } item() { return { item: ITEMS.VIAL_OF_CEASELESS_TOXINS, result: (<dfn data-tip={`The effective damage contributed by Vial of Ceaseless Toxins.<br/>Casts: ${this.totalCasts}<br/> Damage: ${this.owner.formatItemDamageDone(this.damageIncreased)}<br/> Total Damage: ${formatNumber(this.damageIncreased)}`}> {this.owner.formatItemDamageDone(this.damageIncreased)} </dfn>), }; } } export default VialOfCeaselessToxins;
src/svg-icons/maps/local-car-wash.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalCarWash = (props) => ( <SvgIcon {...props}> <path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 13l1.5-4.5h11L19 13H5z"/> </SvgIcon> ); MapsLocalCarWash = pure(MapsLocalCarWash); MapsLocalCarWash.displayName = 'MapsLocalCarWash'; MapsLocalCarWash.muiName = 'SvgIcon'; export default MapsLocalCarWash;
src/parser/warlock/affliction/modules/features/DotUptimes/index.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { STATISTIC_ORDER } from 'interface/others/StatisticsListBox'; import StatisticBar from 'interface/statistics/StatisticBar'; import AgonyUptime from './AgonyUptime'; import CorruptionUptime from './CorruptionUptime'; import UnstableAfflictionUptime from './UnstableAfflictionUptime'; import SiphonLifeUptime from '../../talents/SiphonLifeUptime'; class DotUptimeStatisticBox extends Analyzer { static dependencies = { agonyUptime: AgonyUptime, corruptionUptime: CorruptionUptime, unstableAfflictionUptime: UnstableAfflictionUptime, siphonLifeUptime: SiphonLifeUptime, }; statistic() { return ( <StatisticBar wide position={STATISTIC_ORDER.CORE(1)} > {this.agonyUptime.subStatistic()} {this.corruptionUptime.subStatistic()} {this.unstableAfflictionUptime.subStatistic()} {this.siphonLifeUptime.active && this.siphonLifeUptime.subStatistic()} </StatisticBar> ); } } export default DotUptimeStatisticBox;
client/scenes/ShowcaseScene.js
SLIBIO/SLib-Doc
import React, { Component } from 'react'; import { Grid, Card, CardTitle, CardText } from 'react-mdl'; import { NavigationBar } from '../components'; import styles from '../styles/ShowcaseScene.scss'; import Item1 from '../assets/showcase/item1_1.png'; import Item2 from '../assets/showcase/item2_1.png'; const showcaseItems = [{ backgroundImage: `url(${Item1})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }, { backgroundImage: `url(${Item2})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }, { backgroundImage: `url(${Item1})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }, { backgroundImage: `url(${Item2})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }, { backgroundImage: `url(${Item1})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }, { backgroundImage: `url(${Item2})`, content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenan convallis.' }]; export default class ShowcaseScene extends Component { constructor(props) { super(props); this.navigationRef = null; } onPaneDidMounted = (ref) => { if (ref) { ref.addEventListener('scroll', () => { this.navigationRef.handleScrollPosition(ref.scrollTop); }); } }; renderShowcaseItems() { const ret = []; showcaseItems.forEach((item, index) => { const { title, content, backgroundImage } = item; ret.push( <Card shadow={0} className={`${styles.showcaseItemContainer} ${styles[`item${index % 2}`]}`} > <CardTitle expand className={styles.title} style={{ backgroundImage }}> {title} </CardTitle> <CardText> {content} </CardText> </Card> ); }); return ret; } render() { return ( <div className={styles.container}> <NavigationBar ref={ref => this.navigationRef = ref } /> <div className={styles.mainContainer} ref={this.onPaneDidMounted}> <div className={styles.topHeader}> <div className={styles.titleContainer}> We’re proud to feature amazing apps built with SLib! </div> <div className={styles.titleDescription}> If you have an app to share for the SLib Showcase, please <span className={styles.contactUs}>&nbsp;let us know.</span> </div> </div> <div className={styles.gridContainer}> <Grid> {this.renderShowcaseItems()} <div style={{ width: '300px', height: '100px' }} /> </Grid> </div> </div> </div> ); } }
app/js/sign-out/index.js
blockstack/blockstack-portal
import React from 'react' import PropTypes from 'prop-types' import { withRouter } from 'react-router' import Initial from './views/initial' import { ShellParent } from '@blockstack/ui' const VIEWS = { INITIAL: 0 } const views = [Initial] const SignOut = ({ location }) => { const view = 0 const viewProps = [ { show: VIEWS.INITIAL, props: { backLabel: 'Cancel' } } ] const currentViewProps = viewProps.find(v => v.show === view) || {} const componentProps = { view, backView: () => null, location, ...currentViewProps.props } return ( <> <ShellParent views={views} {...componentProps} disableBackOnView={views.length - 1} /> </> ) } SignOut.propTypes = { location: PropTypes.object, router: PropTypes.object } export default withRouter(SignOut)
public/app/components/base/input-dialog.js
vincent-tr/mylife-wine
import React from 'react'; import PropTypes from 'prop-types'; import * as mui from 'material-ui'; import { confirmable, createConfirmation } from 'react-confirm'; import base from '../base/index'; class InputDialog extends React.Component { constructor(props, context) { super(props, context); this.state = { text: props && props.options && props.options.text }; } componentWillReceiveProps(nextProps) { const { text } = nextProps.options; this.setState({ text }); } render() { const { show, proceed, /*dismiss,*/ cancel, /*confirmation,*/ options } = this.props; const { text } = this.state; return ( <base.Theme> <mui.Dialog title={options.title} actions={<div> <mui.FlatButton label="OK" onTouchTap={() => proceed(text)} /> <mui.FlatButton label="Annuler" onTouchTap={() => cancel()} /> </div>} modal={true} open={show} autoScrollBodyContent={true}> <mui.TextField floatingLabelText={options.label} id="text" value={text || ''} onChange={(event) => this.setState({ text: event.target.value })} /> </mui.Dialog> </base.Theme> ); } } InputDialog.propTypes = { show: PropTypes.bool, // from confirmable. indicates if the dialog is shown or not. proceed: PropTypes.func, // from confirmable. call to close the dialog with promise resolved. cancel: PropTypes.func, // from confirmable. call to close the dialog with promise rejected. dismiss: PropTypes.func, // from confirmable. call to only close the dialog. confirmation: PropTypes.string, // arguments of your confirm function options: PropTypes.object // arguments of your confirm function }; const edit = createConfirmation(confirmable(InputDialog)); export default ({ title, label, text, ...options }) => { edit({ options: { title, label, text } }).then( (text) => (options.proceed && options.proceed(text)), () => (options.cancel && options.cancel())); };
blueprints/dumb/files/__root__/components/__name__/__name__.js
dfalling/todo
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
tests/baselines/reference/reactDefaultPropsInferenceSuccess.js
Microsoft/TypeScript
//// [reactDefaultPropsInferenceSuccess.tsx] /// <reference path="/.lib/react16.d.ts" /> import React from 'react'; interface BaseProps { when?: ((value: string) => boolean) | "a" | "b"; error?: boolean; } interface Props extends BaseProps { } class FieldFeedback<P extends Props = BaseProps> extends React.Component<P> { static defaultProps = { when: () => true }; render() { return <div>Hello</div>; } } // OK const Test1 = () => <FieldFeedback when={value => !!value} />; // Error: Void not assignable to boolean const Test2 = () => <FieldFeedback when={value => console.log(value)} />; class FieldFeedbackBeta<P extends Props = BaseProps> extends React.Component<P> { static defaultProps: BaseProps = { when: () => true }; render() { return <div>Hello</div>; } } // OK const Test1a = () => <FieldFeedbackBeta when={value => !!value} error>Hah</FieldFeedbackBeta>; // Error: Void not assignable to boolean const Test2a = () => <FieldFeedbackBeta when={value => console.log(value)} error>Hah</FieldFeedbackBeta>; interface MyPropsProps extends Props { when: (value: string) => boolean; } class FieldFeedback2<P extends MyPropsProps = MyPropsProps> extends FieldFeedback<P> { static defaultProps = { when: () => true }; render() { this.props.when("now"); // OK, always defined return <div>Hello</div>; } } // OK const Test3 = () => <FieldFeedback2 when={value => !!value} />; // Error: Void not assignable to boolean const Test4 = () => <FieldFeedback2 when={value => console.log(value)} />; // OK const Test5 = () => <FieldFeedback2 />; //// [reactDefaultPropsInferenceSuccess.js] "use strict"; /// <reference path="react16.d.ts" /> var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; var react_1 = __importDefault(require("react")); var FieldFeedback = /** @class */ (function (_super) { __extends(FieldFeedback, _super); function FieldFeedback() { return _super !== null && _super.apply(this, arguments) || this; } FieldFeedback.prototype.render = function () { return react_1["default"].createElement("div", null, "Hello"); }; FieldFeedback.defaultProps = { when: function () { return true; } }; return FieldFeedback; }(react_1["default"].Component)); // OK var Test1 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return !!value; } }); }; // Error: Void not assignable to boolean var Test2 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return console.log(value); } }); }; var FieldFeedbackBeta = /** @class */ (function (_super) { __extends(FieldFeedbackBeta, _super); function FieldFeedbackBeta() { return _super !== null && _super.apply(this, arguments) || this; } FieldFeedbackBeta.prototype.render = function () { return react_1["default"].createElement("div", null, "Hello"); }; FieldFeedbackBeta.defaultProps = { when: function () { return true; } }; return FieldFeedbackBeta; }(react_1["default"].Component)); // OK var Test1a = function () { return react_1["default"].createElement(FieldFeedbackBeta, { when: function (value) { return !!value; }, error: true }, "Hah"); }; // Error: Void not assignable to boolean var Test2a = function () { return react_1["default"].createElement(FieldFeedbackBeta, { when: function (value) { return console.log(value); }, error: true }, "Hah"); }; var FieldFeedback2 = /** @class */ (function (_super) { __extends(FieldFeedback2, _super); function FieldFeedback2() { return _super !== null && _super.apply(this, arguments) || this; } FieldFeedback2.prototype.render = function () { this.props.when("now"); // OK, always defined return react_1["default"].createElement("div", null, "Hello"); }; FieldFeedback2.defaultProps = { when: function () { return true; } }; return FieldFeedback2; }(FieldFeedback)); // OK var Test3 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return !!value; } }); }; // Error: Void not assignable to boolean var Test4 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return console.log(value); } }); }; // OK var Test5 = function () { return react_1["default"].createElement(FieldFeedback2, null); };
src/CheckBox/CheckBox.stories.js
ctco/rosemary-ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import CheckBox from './CheckBox'; storiesOf('CheckBox', module) .add('Checked', () => <CheckBox onChange={action('onChange')} checked title="This is Title" />) .add('Disabled', () => <CheckBox title="title title" checked disabled />) .add('Uncontrolled CheckBox', () => <CheckBox />);
src/svg-icons/content/block.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentBlock = (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 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"/> </SvgIcon> ); ContentBlock = pure(ContentBlock); ContentBlock.displayName = 'ContentBlock'; ContentBlock.muiName = 'SvgIcon'; export default ContentBlock;
src/components/Feedback/Feedback.js
bingomanatee/ReactUserBoilerplate
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
src/components/OrganizationLogo/OrganizationLogo.js
folio-org/stripes-core
import React from 'react'; import { branding } from 'stripes-config'; import styles from './OrganizationLogo.css'; const OrganizationLogo = () => { return ( branding && <div className={styles.logo}> <img alt={branding.logo.alt} src={branding.logo.src} /> </div> ); }; export default OrganizationLogo;
src/index.js
bcbcb/react-hot-boilerplate
import React from 'react'; import App from './App'; React.render(<App />, document.getElementById('root'));
app/src/client/app/framework/PagerPresentation.js
syrel/Open-Data
/** * Created by syrel on 15.05.17. */ import React from 'react'; import ReactDOM from 'react-dom'; import _ from 'underscore'; import $ from 'jquery'; import CompositePresentation from './CompositePresentation'; import Thenable from './../Thenable' class PagerComponent extends CompositePresentation.CompositeComponent { constructor(props) { super(props); this.cache = { scrollTo: _.noop() }; } render() { return ( <div style={{ whiteSpace: 'nowrap', overflowX: 'auto', height: '100%', position: 'absolute', width: '100%' }}> { this.presentations().map((presentation, index) => ( <div className='pager-pane' ref={ 'pane' + index } key={index}> { presentation.render() } </div> )) } </div> ); } scrollToLast(animated) { animated = _.isUndefined(animated) ? true : animated; const lastPane = this.refs['pane' + (this.presentations().length-1)]; const pager = ReactDOM.findDOMNode(this); this.presentation().state.scrollToLast = { scroll: false, animated: false }; var scrollLeft = () => { return $(pager).scrollLeft() + $(lastPane).offset().left + $(lastPane).width(); }; if (animated) { $(pager).animate({ scrollLeft: scrollLeft() }, 750); } else { $(pager).scrollLeft(scrollLeft()); } }; componentDidUpdate() { if (!this.presentation().state.scrollToLast.scroll) { return; } if (!this.presentation().state.scrollToLast.animated) { return this.scrollToLast(false); } const scrollToThenable = Thenable.delay(50).then(() => { if (this.presentations().length < 1) { return; } if (scrollToThenable !== this.cache.scrollTo) { return; } this.scrollToLast(this.presentation().state.scrollToLast.animated); }); this.cache.scrollTo = scrollToThenable; } } class PagerPresentation extends CompositePresentation { constructor(props) { super(props); Object.assign(this.state, { scrollToLast: { scroll: true, animated: false } }); } add(presentation) { super.add(presentation); } // return presentation pane that contains a given presentation paneOf(presentation) { return _.find(this.presentations, each => presentation.hasGivenOwner(each)); } // pops all presentations after a given one popAfter(presentation) { var index = this.indexOf(presentation); if (index < -1) { return; } for (var i = this.presentations.length - 1; i > index; i--) { this.remove(this.presentations[i]); } } scrollToLast(isAnimated) { this.state.scrollToLast = { scroll: true, animated: isAnimated }; this.updateComponent(); } render() { return (<PagerComponent key={ this.uuid() } bind={ this.bindings() } />); } } export default PagerPresentation;
2-alpha/src/Features/Form/PrimerPreviewSmall.js
saturninoharris/primer-design
import React from 'react' import { connect } from 'react-redux' import styled from 'styled-components' import { Sequence } from '../../components/Sequence' const Container = styled.div` text-align: center; ` const PrimerPreviewSmall = ({ strand, plasmidSegment, geneSegment, animatingPreview }) => { const displayBases = (bases = '') => bases.split('').map((l,i) => <span className="l" key={i}>{l}</span> ) const activeClass = animatingPreview ? 'active' : '' if(strand === 'reverse') { return ( <Container className={`primer-preview primer-preview-reverse ` + activeClass}> <Sequence className='RV'> <span className='prime-5 l'>5</span> <span className='prime-5 l'>-</span> {displayBases(plasmidSegment)} </Sequence> <Sequence className='RG'> {displayBases(geneSegment)} <span className='prime-3 l'>-</span> <span className='prime-3 l'>3</span> </Sequence> </Container> ) } if(strand === 'forward') { // doing a double if because I dont like silent errors. return ( <Container> <Sequence className='FV'> <span className='prime-5'>5</span> <span className='prime-5'>-</span> {displayBases(plasmidSegment)} </Sequence> <Sequence className='FG'> {displayBases(geneSegment)} <span className='prime-3'>-</span> <span className='prime-3'>3</span> </Sequence> </Container> ) } } const mapStateToProps = ({formInputs, animatingPreview }, ownProps) => { const plasmidSegment = ownProps.strand === 'forward' ? 'FV' : 'RV' const geneSegment = ownProps.strand === 'forward' ? 'FG' : 'RG' return { strand: ownProps.strand, plasmidSegment: formInputs[plasmidSegment], geneSegment: formInputs[geneSegment], animatingPreview } } export default connect(mapStateToProps)(PrimerPreviewSmall)
packages/plugins/users-permissions/admin/src/components/FormModal/Input/index.js
wistityhq/strapi
/** * * Input * */ import React from 'react'; import { useIntl } from 'react-intl'; import { ToggleInput } from '@strapi/design-system/ToggleInput'; import { TextInput } from '@strapi/design-system/TextInput'; import PropTypes from 'prop-types'; const Input = ({ description, disabled, intlLabel, error, name, onChange, placeholder, providerToEditName, type, value, }) => { const { formatMessage } = useIntl(); const inputValue = name === 'noName' ? `${strapi.backendURL}/connect/${providerToEditName}/callback` : value; const label = formatMessage( { id: intlLabel.id, defaultMessage: intlLabel.defaultMessage }, { provider: providerToEditName, ...intlLabel.values } ); const hint = description ? formatMessage( { id: description.id, defaultMessage: description.defaultMessage }, { provider: providerToEditName, ...description.values } ) : ''; if (type === 'bool') { return ( <ToggleInput aria-label={name} checked={value} disabled={disabled} hint={hint} label={label} name={name} offLabel={formatMessage({ id: 'app.components.ToggleCheckbox.off-label', defaultMessage: 'Off', })} onLabel={formatMessage({ id: 'app.components.ToggleCheckbox.on-label', defaultMessage: 'On', })} onChange={e => { onChange({ target: { name, value: e.target.checked } }); }} /> ); } const formattedPlaceholder = placeholder ? formatMessage( { id: placeholder.id, defaultMessage: placeholder.defaultMessage }, { ...placeholder.values } ) : ''; const errorMessage = error ? formatMessage({ id: error, defaultMessage: error }) : ''; return ( <TextInput aria-label={name} disabled={disabled} error={errorMessage} label={label} name={name} onChange={onChange} placeholder={formattedPlaceholder} type={type} value={inputValue} /> ); }; Input.defaultProps = { description: null, disabled: false, error: '', placeholder: null, value: '', }; Input.propTypes = { description: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), disabled: PropTypes.bool, error: PropTypes.string, intlLabel: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }).isRequired, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, placeholder: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), providerToEditName: PropTypes.string.isRequired, type: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), }; export default Input;
src/scenes/Home.js
sunilgautam/ReduxTodo
'use strict'; import React, { Component } from 'react'; import { StyleSheet, View, } from 'react-native'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as ActionCreators from '../actions'; import TodoList from '../components/TodoList'; import InputSection from '../components/InputSection'; class Home extends Component { render() { return ( <View style={styles.container}> <InputSection ref="inputSection" {...this.props} /> <TodoList {...this.props} onEmptyClick={() => {this.refs.inputSection.setFocusToInput()}} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', padding: 5, }, }); function mapStateToProps(state) { return { todos: state.todos, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(ActionCreators, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(Home);
src/utils/index.js
kimf/golfstats_client_react_redux_immutable
import React from 'react'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; export function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no' ); // reload in case it's reusing the same window with the old content win.location.reload(); // wait a little bit for it to reload, then render setTimeout(() => { React.render( <DebugPanel top right bottom left > <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> , win.document.body); }, 10); }
src/components/pages/Wiki0/Info/index.js
humaniq/humaniq-pwa-website
import React from 'react'; import * as T from "prop-types"; import './styles.scss'; import {cssClassName} from 'utils' const cn = cssClassName('SE_WikiInfo') import A_Link from 'A_Link' import A_Image from 'A_Image' import A_H from 'A_H' const SE_WikiInfo = ({children, type, img, title, link, external}) =>{ const moving = type == 'moving-title' return ( <div className={cn('root')}> <div className={cn('body')}> <span className={moving && "mobile-hide"}> <A_H type="section">{title}</A_H> </span> {children} <A_Link type="section-link" to={link.to} external={external}>{link.text}</A_Link> </div> <div className={cn('img-side', {type})}> {moving && <span className="mobile-show"> <A_H type="section">{title}</A_H> </span> } <div className={cn('img')}> <A_Image {...img} /> </div> </div> </div> ) } SE_WikiInfo.propTypes = { type: T.oneOf([ 'moving-title', //title changes place on mobile devices 'hidding-img', //img is hidding on mobile devices ]).isRequired, children: T.node.isRequired, title: T.string, img: T.shape({ src: T.string.isRequired, alt: T.string.isRequired }).isRequired, link: T.shape({ to: T.string.isRequired, text: T.string.isRequired }) }; SE_WikiInfo.defaultProps = { } export default SE_WikiInfo
src/svg-icons/notification/do-not-disturb.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturb = (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 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/> </SvgIcon> ); NotificationDoNotDisturb = pure(NotificationDoNotDisturb); NotificationDoNotDisturb.displayName = 'NotificationDoNotDisturb'; NotificationDoNotDisturb.muiName = 'SvgIcon'; export default NotificationDoNotDisturb;
src/PaginationButton.js
egauci/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import createSelectedEvent from './utils/createSelectedEvent'; import elementType from 'react-prop-types/lib/elementType'; const PaginationButton = React.createClass({ propTypes: { className: React.PropTypes.string, eventKey: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, active: React.PropTypes.bool, /** * You can use a custom element for this component */ buttonComponentClass: elementType }, getDefaultProps() { return { active: false, disabled: false }; }, handleClick(event) { if (this.props.disabled) { return; } if (this.props.onSelect) { let selectedEvent = createSelectedEvent(this.props.eventKey); this.props.onSelect(event, selectedEvent); } }, render() { let classes = { active: this.props.active, disabled: this.props.disabled }; let { className, ...anchorProps } = this.props; let ButtonComponentClass = this.props.buttonComponentClass; return ( <li className={classNames(className, classes)}> <ButtonComponentClass {...anchorProps} onClick={this.handleClick} /> </li> ); } }); export default PaginationButton;
app/javascript/mastodon/features/community_timeline/index.js
primenumber/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandCommunityTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectCommunityStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.community', defaultMessage: 'Local timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'community', 'other', 'onlyMedia']); const timelineState = state.getIn(['timelines', `community${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, }; }; export default @connect(mapStateToProps) @injectIntl class CommunityTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, columnId: PropTypes.string, intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, onlyMedia: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('COMMUNITY', { other: { onlyMedia } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia } = this.props; dispatch(expandCommunityTimeline({ onlyMedia })); this.disconnect = dispatch(connectCommunityStream({ onlyMedia })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia) { const { dispatch, onlyMedia } = this.props; this.disconnect(); dispatch(expandCommunityTimeline({ onlyMedia })); this.disconnect = dispatch(connectCommunityStream({ onlyMedia })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia } = this.props; dispatch(expandCommunityTimeline({ maxId, onlyMedia })); } render () { const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn, onlyMedia } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='users' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`community_timeline-${columnId}`} timelineId={`community${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
js/apps/system/_admin/aardvark/APP/react/src/App.js
Simran-B/arangodb
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; // import Overview from './views/shards/overview'; const jsoneditor = require('jsoneditor'); const d3 = require('d3'); const nvd3 = require('nvd3'); // parse prometheus const parsePrometheusTextFormat = require('parse-prometheus-text-format'); window.parsePrometheusTextFormat = parsePrometheusTextFormat; // import new react views require('./views/shards/ShardsReactView'); // old libraries const jQuery = require('jquery'); const Backbone = require('backbone'); const _ = require('underscore'); const Sigma = require('sigma'); const Noty = require('noty'); const Marked = require('marked'); const CryptoJS = require('crypto-js'); // highlight.js const hljs = require('highlight.js/lib/highlight'); const json = require('highlight.js/lib/languages/json'); const env = process.env.NODE_ENV // import old based css files require('../../frontend/css/pure-min.css'); require('../../frontend/ttf/arangofont/style.css'); require('../../frontend/css/bootstrap.css'); require('../../frontend/css/jquery.contextmenu.css'); require('../../frontend/css/select2.css'); require('../../frontend/css/highlightjs.css'); require('../../frontend/css/jsoneditor.css'); require('../../frontend/css/tippy.css'); require('../../frontend/css/dygraph.css'); require('../../frontend/css/leaflet.css'); require('../../frontend/css/nv.d3.css'); require('../../frontend/css/grids-responsive-min.css'); // import sass files require('../../frontend/scss/style.scss'); require('highlight.js/styles/github.css'); // noty css require("../node_modules/noty/lib/noty.css"); require("../node_modules/noty/lib/themes/sunset.css"); window.JST = {}; function requireAll(context) { context.keys().forEach(context); _.each(context.keys(), function(key) { // detect and store ejs templates if (key.substring(key.length - 4, key.length) === '.ejs') { let filename = key.substring(2, key.length); let name = key.substring(2, key.length - 4); if (env === 'development') { window.JST['templates/' + name] = _.template(require('../../frontend/js/templates/' + filename).default); } else { // production - precompiled templates window.JST['templates/' + name] = require('../../frontend/js/templates/' + filename); } } }); } // templates ejs requireAll(require.context( '../../frontend/js/templates/' )); /** * `require` all backbone dependencies */ hljs.registerLanguage('json', json); window.hljs = hljs; window.Noty = Noty; window.ReactDOM = ReactDOM; window.Joi = require('../../frontend/js/lib/joi-browser.min.js'); window.jQuery = window.$ = jQuery; window.parsePrometheusTextFormat = parsePrometheusTextFormat; require('../../frontend/js/lib/select2.min.js'); window._ = _; require('../../frontend/js/arango/templateEngine.js'); require('../../frontend/js/arango/arango.js'); // only set this for development if (window.frontendConfig && env === 'development') { window.frontendConfig.basePath = process.env.REACT_APP_ARANGODB_HOST; window.frontendConfig.react = true; } require('../../frontend/js/lib/jquery-ui-1.9.2.custom.min.js'); require('../../frontend/js/lib/jquery.form.js'); require('../../frontend/js/lib/jquery.uploadfile.min.js'); require('../../frontend/js/lib/bootstrap-min.js'); // typeahead require("typeahead.js/dist/typeahead.jquery.min.js") require("typeahead.js/dist/bloodhound.min.js") // Collect all Backbone.js related require('../../frontend/js/routers/router.js'); require('../../frontend/js/routers/versionCheck.js'); require('../../frontend/js/routers/startApp.js'); requireAll(require.context( '../../frontend/js/views/' )); requireAll(require.context( '../../frontend/js/models/' )); requireAll(require.context( '../../frontend/js/collections/' )); // Third Party Libraries window.tippy = require('tippy.js'); require('../../frontend/js/lib/bootstrap-pagination.min.js'); window.numeral = require('../../frontend/js/lib/numeral.min.js'); // TODO window.JSONEditor = jsoneditor; // ace window.define = window.ace.define; window.aqltemplates = require('../public/assets/aqltemplates.json'); window.d3 = d3; require('../../frontend/js/lib/leaflet.js') require('../../frontend/js/lib/tile.stamen.js') window.prettyBytes = require('../../frontend/js/lib/pretty-bytes.js'); window.Dygraph = require('../../frontend/js/lib/dygraph-combined.min.js'); require('../../frontend/js/config/dygraphConfig.js'); window.moment = require('../../frontend/js/lib/moment.min.js'); // sigma window.sigma = Sigma; window.marked = Marked; window.CryptoJS = CryptoJS; // import additional sigma plugins require('sigma/build/plugins/sigma.layout.forceAtlas2.min'); // workaround to work with webpack // additional sigma plugins require('../../frontend/js/lib/sigma.canvas.edges.autoCurve.js'); require('../../frontend/js/lib/sigma.canvas.edges.curve.js'); require('../../frontend/js/lib/sigma.canvas.edges.dashed.js'); require('../../frontend/js/lib/sigma.canvas.edges.dotted.js'); require('../../frontend/js/lib/sigma.canvas.edges.labels.curve.js'); require('../../frontend/js/lib/sigma.canvas.edges.labels.curvedArrow.js'); require('../../frontend/js/lib/sigma.canvas.edges.labels.def.js'); require('../../frontend/js/lib/sigma.canvas.edges.tapered.js'); require('../../frontend/js/lib/sigma.exporters.image.js'); require('../../frontend/js/lib/sigma.layout.fruchtermanReingold.js'); require('../../frontend/js/lib/sigma.layout.noverlap.js'); require('../../frontend/js/lib/sigma.plugins.animate.js'); require('../../frontend/js/lib/sigma.plugins.dragNodes.js'); require('../../frontend/js/lib/sigma.plugins.filter.js'); require('../../frontend/js/lib/sigma.plugins.fullScreen.js'); require('../../frontend/js/lib/sigma.plugins.lasso.js'); require('../../frontend/js/lib/sigma.renderers.halo.js'); require('../../frontend/js/lib/jquery.csv.min.js'); require('../../frontend/js/lib/wheelnav.slicePath.js'); require('../../frontend/js/lib/wheelnav.min.js'); window.Raphael = require('../../frontend/js/lib/raphael.min.js'); window.icon = require('../../frontend/js/lib/raphael.icons.min.js'); window.randomColor = require('../../frontend/js/lib/randomColor.js'); //require('../../frontend/src/ace.js'); //require('../../frontend/src/theme-textmate.js'); //require('../../frontend/src/mode-json.js'); //require('../../frontend/src/mode-aql.js'); class App extends Component { // <Overview /> render() { return ( <div className="App"></div> ); } } export default App;
docs/src/sections/ValidateRefersResetSection.js
yyssc/ssc-grid
import React from 'react'; import Anchor from '../Anchor'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ValidateRefersResetSection() { return ( <div className="bs-docs-section"> <h3><Anchor id="validate-refers-reset">重置参照</Anchor></h3> <ReactPlayground codeText={Samples.ValidateRefersReset} /> </div> ); }
packages/ringcentral-widgets-docs/src/app/pages/Components/EntityModal/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/EntityModal'; const EntityModalPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="EntityModal" description={info.description} /> <CodeExample code={demoCode} title="EntityModal Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default EntityModalPage;
src/components/Search/Logo/index.js
alantva/meli
import React from 'react'; import Src from '../../../assets/images/mercado-libre.png'; const Logo = props => ( <img {...props} src={Src} alt="Logo ML" /> ); export default Logo;
fields/types/password/PasswordFilter.js
everisARQ/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; const EXISTS_OPTIONS = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false }, ]; function getDefaultValue () { return { exists: true, }; } var PasswordFilter = React.createClass({ propTypes: { filter: React.PropTypes.shape({ exists: React.PropTypes.oneOf(EXISTS_OPTIONS.map(i => i.value)), }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, toggleExists (value) { this.props.onChange({ exists: value }); }, render () { const { filter } = this.props; return <SegmentedControl equalWidthSegments options={EXISTS_OPTIONS} value={filter.exists} onChange={this.toggleExists} />; }, }); module.exports = PasswordFilter;
src/components/Contact.js
carlyleec/cc-react
import React from 'react'; import styled from 'styled-components'; import Container from './Container'; import ImageCollection from './ImageCollection'; const SocialImage = styled.img` height: 50px; width: 50px; `; const ContactWrapper = styled.div` display: flex; flex-wrap: wrap; justify-content: center; align-items: center; height: 90vh; `; const ContactContent = styled.div` flex: 1 1 100%; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; `; const EmailLink = styled.a` font-size: 2em; flex: 1 1 100%; text-decoration: none; font-weight: 700; color: #03A9F4; text-align: center; margin: auto; `; const Name = styled.h1` text-align: center; color: #90A4AE; flex: 1 1 100%; `; const ResumeLink = styled.a` font-size: 1em; flex: 1 1 100%; text-decoration: none; font-weight: 700; color: #03A9F4; margin: auto; text-align: center; `; const Contact = () => ( <Container> <ContactWrapper> <ContactContent> <Name>CAMERON CARLYLE</Name> <EmailLink href="mailto:carlyleec@gmail.com">carlyleec@gmail.com</EmailLink> <ImageCollection> <a target="_blank" href="https://github.com/carlyleec"> <SocialImage alt="Github" src="/assets/images/github_1492206232253.png"></SocialImage> </a> <a target="_blank" href="https://www.instagram.com/_cameroncarlyle/"> <SocialImage alt="Instagram" src="assets/images/instagram_1492206330714.png"></SocialImage> </a> <a target="_blank" href="https://twitter.com/carlyleec"> <SocialImage alt="Twitter" src="assets/images/twitter_1492206564080.png"></SocialImage> </a> <a target="_blank" href="https://www.facebook.com/cameron.carlyle"> <SocialImage alt="Facebook" src="assets/images/fb_1492206437340.png"></SocialImage> </a> </ImageCollection> <ResumeLink target="_blank" href="/cameron-carlyle-resume.pdf">Download Resume</ResumeLink> </ContactContent> </ContactWrapper> </Container> ); Contact.propTypes = {}; export default Contact;
_src/components/TopNav/index.js
apedyashev/react-universal-jobs-aggregator
// libs import React from 'react'; import {PropTypes} from 'prop-types'; // components import NotAuthenticated from './NotAuthenticated'; import Authenticated from './Authenticated'; export default function TopNav({alwaysSticked, isAuthenticated}) { return isAuthenticated ? ( <Authenticated alwaysSticked={alwaysSticked} /> ) : ( <NotAuthenticated alwaysSticked={alwaysSticked} /> ); } TopNav.propTypes = { alwaysSticked: PropTypes.bool, isAuthenticated: PropTypes.bool, };
js/screens/NotificationsScreenComponents/NotificationRow.js
ujwalramesh/REHU-discourse
/* @flow */ 'use strict' import React from 'react' import { Image, StyleSheet, Text, TouchableHighlight, View } from 'react-native' import Icon from 'react-native-vector-icons/FontAwesome' import DiscourseUtils from '../../DiscourseUtils' class NotificationRow extends React.Component { render() { return ( <TouchableHighlight style={[styles.contentView, this._backgroundColor()]} underlayColor={'#ffffa6'} onPress={()=>this.props.onClick()}> <View style={styles.container}> {this._iconForNotification(this.props.notification)} {this._textForNotification(this.props.notification)} <Image style={styles.siteIcon} source={{uri: this.props.site.icon}} /> </View> </TouchableHighlight> ) } _iconForNotification(notification) { let name = DiscourseUtils.iconNameForNotification(notification) return <Icon style={styles.notificationIcon} name={name} size={14} color="#919191" /> } _textForNotification(notification) { let innerText let data = this.props.notification.data let displayName = data.display_username if (notification.notification_type === 5) { // special logic for multi like if (data.count === 2) { displayName = `${displayName} and ${data.username2}` } else if (data.count > 2) { let other = data.count == 2 ? 'other' : 'others' displayName = `${displayName}, ${data.username2} and ${data.count - 2} ${other}` } } switch (notification.notification_type) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 13: case 14: case 15: case 17: innerText = ( <Text> {displayName} <Text style={styles.notificationText}> {' '}{this.props.notification.data.topic_title} </Text> </Text> ) break case 12: innerText = ( <Text style={styles.notificationText}> {' '}{this.props.notification.data.badge_name} </Text> ) break case 16: let messages = data.inbox_count > 1 ? 'messages' : 'message' innerText = ( <Text style={styles.notificationText}> {`${data.inbox_count} ${messages} in your ${data.group_name} inbox`} </Text> ) break default: console.log('Couldn’t generate text for notification', notification) innerText = <Text>Unmapped type: {notification.notification_type}</Text> } return <Text style={styles.textContainer}>{innerText}</Text> } _backgroundColor() { let read = this.props.notification.read if (read) { return {backgroundColor: 'white'} } else { return {backgroundColor: '#d1f0ff'} } } } const styles = StyleSheet.create({ contentView: { borderBottomColor: '#ddd', borderBottomWidth: StyleSheet.hairlineWidth }, textContainer: { flex: 1, flexDirection: 'column', alignSelf: 'center', fontSize: 14 }, notificationText: { color: '#08c', }, container: { flex: 1, flexDirection: 'row', margin: 12 }, siteIcon: { width: 25, height: 25, alignSelf: 'center', marginLeft: 12 }, notificationIcon: { alignSelf: 'center', marginRight: 12 } }) export default NotificationRow
demo/src/components/Main.js
burakcan/react-snowstorm
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import SnowStorm from 'react-snowstorm'; import 'normalize.css'; import 'styles/global' export default class Main extends Component { render() { return ( <main> <h1 ref='title'>React-snowstorm</h1> <h2 ref='subtitle'>A Snow Effect component for React.</h2> <SnowStorm /> </main> ) } }
newclient/scripts/components/config/general/expand-instructions-toggle/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import ConfigActions from '../../../../actions/config-actions'; export default function ExpandInstructionsToggle(props) { return ( <div className={styles.container}> <input type="checkbox" id="expandInstructionByDefault" checked={props.checked} onChange={ConfigActions.toggleInstructionsExpanded} className={styles.checkbox} /> <label htmlFor="expandInstructionByDefault" className={styles.label}> Expand instructions by default </label> </div> ); }
src/components/SocialLinks.js
akhatri/portfolio-website
import React from 'react'; import '../styles/social-links.scss' const SocialLinks = (props) => { return ( <ul className="social-links"> { props.socialData ? props.socialData.map( (item, index)=> <li key={index}> <a href={item.link} title={item.title} target="_blank" rel="noopener noreferrer"> <i aria-hidden="true" className={`${item.icon} icon`}></i> </a> </li> ) : '' } </ul> ) } export default SocialLinks;
src/parser/warlock/affliction/modules/azerite/WrackingBrilliance.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import { calculateAzeriteEffects } from 'common/stats'; import { formatPercentage } from 'common/format'; import TraitStatisticBox from 'interface/others/TraitStatisticBox'; const wrackingBrillianceStats = traits => traits.reduce((total, rank) => { const [ intellect ] = calculateAzeriteEffects(SPELLS.WRACKING_BRILLIANCE.id, rank); return total + intellect; }, 0); export const STAT_TRACKER = { intellect: combatant => wrackingBrillianceStats(combatant.traitsBySpellId[SPELLS.WRACKING_BRILLIANCE.id]), }; const debug = false; /* Wracking Brilliance: Every other Soul Shard your Agony generates also increases your Intellect by X for 6 sec. */ class WrackingBrilliance extends Analyzer { intellect = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.WRACKING_BRILLIANCE.id); if (!this.active) { return; } this.intellect = wrackingBrillianceStats(this.selectedCombatant.traitsBySpellId[SPELLS.WRACKING_BRILLIANCE.id]); debug && this.log(`Total bonus from WB: ${this.intellect}`); } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.WRACKING_BRILLIANCE_BUFF.id) / this.owner.fightDuration; } get averageIntellect() { return (this.uptime * this.intellect).toFixed(0); } statistic() { return ( <TraitStatisticBox trait={SPELLS.WRACKING_BRILLIANCE.id} value={`${this.averageIntellect} average Intellect`} tooltip={`Wracking Brilliance grants ${this.intellect} Intellect while active. You had ${formatPercentage(this.uptime)} % uptime on the buff.`} /> ); } } export default WrackingBrilliance;