path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/action/card-membership.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCardMembership = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V4h16v6z"/> </SvgIcon> ); ActionCardMembership = pure(ActionCardMembership); ActionCardMembership.displayName = 'ActionCardMembership'; ActionCardMembership.muiName = 'SvgIcon'; export default ActionCardMembership;
lib/ui/components/common/MethodLabel.js
500tech/mimic
import React from 'react'; import styled from 'styled-components'; import { Div } from 'ui/components/common/base'; const Label = styled(Div)` font-size: 10px; font-weight: 600; min-width: 37px; width: 37px; user-select: none; text-transform: uppercase; ${(props) => props.failed ? 'color: ' + props.theme.red + ';' : ''} ${(props) => props.mocked ? 'color: ' + props.theme.mockedBlue + ';' : ''} `; const MethodLabel = ({ children, mocked, failed }) => ( <Label mocked={ mocked } failed={ failed }> { children === 'DELETE' ? 'DEL.' : children } </Label> ); export default MethodLabel;
components/Modes/TriviaGame.js
whatever555/countries
import React, { Component } from 'react'; import TopIcon from '../TopIcon'; import { translate } from '../../helpers/translate'; import { ResultBox, ContentHolder, NoScriptLink, FlagHolder, ListButton, ListItem, List, QuestionBox, } from '../../common/styles'; import styled from 'styled-components'; import RightWrong from './RightWrong'; class TriviaGame extends Component { constructor(props) { super(props); } render() { let { countries, ansFunc, answer, score, maxScore, infoLink, nextQuestionLink, rightWrongMessage = null, } = this.props; const correctName = answer.name; const alpha2Code = answer.alpha2Code; return ( <div> {countries.length ? ( <div key={'div8'}> <FlagHolder> <TopIcon iconName={'trivia'} /> {answer.result && ( <RightWrong message={rightWrongMessage} answer={answer} score={score} maxScore={maxScore} /> )} </FlagHolder> {!answer.result && ( <QuestionBox key="qbox">{answer.trivia}</QuestionBox> )} <ContentHolder> <List> {countries.map(function(item, i) { return ( <ListItem key={'Trivia-item' + i + Math.random()}> <ListButton correct={ answer.result ? item.name == correctName ? 'correct' : 'wrong' : false } onClick={() => ansFunc(item.name == correctName)} key={'lk' + i} > {item.name} <noscript> <NoScriptLink href={`/${ answer.name != item.name ? nextQuestionLink : infoLink }`} > [click] </NoScriptLink> </noscript> </ListButton> </ListItem> ); })} </List> </ContentHolder> </div> ) : ( <div>Loading</div> )} </div> ); } } export default TriviaGame;
src/routes/content/media/detail/index.js
muidea/magicSite
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'dva/router' import { connect } from 'dva' import { Button } from 'antd' import styles from './index.less' import { EditableTagGroup } from '../../../../components' const Detail = ({ mediaDetail }) => { const { name, fileUrl, expiration, description, catalog, createDate, creater } = mediaDetail return (<div className="content-inner"> <div className={styles.content}> <div className={styles.item}> <div>名称</div> <div>{name}</div> </div> <div className={styles.item}> <div>分类</div> <div><EditableTagGroup readOnly value={catalog} /></div> </div> <div className={styles.item}> <div>描述</div> <div>{description}</div> </div> <div className={styles.item}> <div>创建时间</div> <div>{createDate}</div> </div> <div className={styles.item}> <div>创建人</div> <div>{creater.name}</div> </div> <div className={styles.item}> <div>有效期(天)</div> <div>{expiration}</div> </div> <div className={styles.item}> <div>下载文件</div> <div><Button style={{ border: 0 }} size="large" icon="download" target="_blank" href={fileUrl} /></div> </div> <div className={styles.item}> <Link to={'/content/media/'} style={{ width: '100%' }}><Button type="dashed" style={{ width: '100%', marginBottom: 8 }} >返回</Button></Link> </div> </div> </div>) } Detail.propTypes = { mediaDetail: PropTypes.object, } export default connect(({ mediaDetail, loading }) => ({ mediaDetail, loading: loading.models.mediaDetail }))(Detail)
src/components/Footer/Footer.js
foxleigh81/foxweb
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© MMVII Alexander Foxleigh</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/"> Home </Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/admin"> Admin </Link> </div> </div> ); } } export default withStyles(s)(Footer);
website/src/components/explorables/season1/episode1/index.js
jwngr/notreda.me
import _ from 'lodash'; import React from 'react'; import {Helmet} from 'react-helmet'; import Table from '../../../charts/Table'; import BarChart from '../../../charts/BarChart'; import InternalLink from '../../../common/InternalLink'; import NewsletterSignupForm from '../../../common/NewsletterSignupForm'; import { P, Note, Stat, Image, Title, Byline, Caption, Heading, Divider, Wrapper, Subtitle, StatsWrapper, SectionTitle, StyledExternalLink, } from '../../index.styles'; import data from './data.json'; import schedule2016Image from '../../../../images/explorables/season1/episode1/schedule2016.png'; const title = 'Down To The Wire'; const subtitle = 'One Possession Games In The Brian Kelly Era'; export default () => { return ( <Wrapper> <Helmet> <title>{`${title} | notreda.me`}</title> </Helmet> <Heading> <a href="/explorables">Explorables</a> <p>Season 1, Episode 1</p> </Heading> <Title>{title}</Title> <Subtitle maxWidth="330px">{subtitle}</Subtitle> <Byline> <p>September 27, 2018</p> <StyledExternalLink href="https://jwn.gr">Jacob Wenger</StyledExternalLink> </Byline> <P> Life as a Notre Dame football fan can be stressful. It sometimes feels like we are in a heated contest each and every weekend, this most recent{' '} <StyledExternalLink href="/2018/4">blowout victory over Wake Forest</StyledExternalLink>{' '} being the exception, not the norm. But is watching your team compete in close games just part of life as a college football fan? Many Irish fans appear not to think so. Although the Irish enter the fifth weekend of this 2018 season with an undefeated record, Brian Kelly has been the target of a criticism that has been common during his tenure as the Irish head coach: his team plays in too many close games, often playing down to the level of inferior opponents. </P> <P> Look no further back than the{' '} <StyledExternalLink href="/2016">2016 season</StyledExternalLink> for how this can go terribly wrong. Despite finishing the season with an overall point differential of +37, the Irish managed a meager 4-8 record and it felt like Kelly was on the verge of losing his job. While a lot went wrong that season, an abysmal 1-7 record in one possession games - defined as those whose final score is within 8 points or fewer - is largely to blame. </P> <InternalLink href="/2016"> <Image src={schedule2016Image} alt="Notre Dame Football 2016 season results" title="Notre Dame Football 2016 season results" /> </InternalLink> <Caption> Notre Dame's 4-8 record in 2016 was due in large part to a 1-7 record in one possession games. </Caption> <P> This season's team is touting a much improved 3-0 record in such games, including an{' '} <StyledExternalLink href="/2018/1">opening weekend victory</StyledExternalLink> against the currently 14th ranked Michigan. But the offense looked anemic in nail-biter victories over{' '} <StyledExternalLink href="/2018/2">Ball State</StyledExternalLink> and{' '} <StyledExternalLink href="/2018/3">Vanderbilt</StyledExternalLink>, two opponents who won't even sniff the top 25 this season. A stroke of bad luck or a single missed tackle could turn close wins like those into painful losses. And even when the Irish hold on to win, it is hard to quantify the impact it has on the team over the course of the season. Increased wear and tear on starters - or, worse yet, injuries at the tail end of games - may be avoided if they were watching from the bench during the fourth quarter because they took care of business in the first three. </P> <P> But is this particular criticism of Brian Kelly's coaching actually fair? Do Kelly's team really play in more close games than expected? </P> <SectionTitle>One Possession Games In The BK Era</SectionTitle> <P> Let's start by quantifying the number of one possession games Notre Dame has actually played with Kelly at the helm. Heading into this weekend's top 10 matchup against Stanford in Kelly's ninth season, he has accrued an overall record of 73-34, good for a win percentage of 68.2%. Note that this figure includes Notre Dame's vacated wins from the 2012-13 seasons since they are just as relevant in this analysis. Of those 107 games since 2010, 49 have been been decided by 8 points or fewer, an anxiety-inducing 45.8% of all games. 2016 certainly had the most, but outside of 2017, one possession games are a consistent trend for Kelly. </P> <BarChart data={data.nd.brianKellyEra.onePossessionGameCounts} xAxisLabel="Season" yAxisLabel="One Possession Games" xAxisTickLabels={['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']} margins={{left: 60, sm: {left: 48}}} /> <Caption> Notre Dame has played in a lot of games under Brian Kelly which were decided by a single possession. </Caption> <P> It almost seems obvious to note that it takes just one play to change the outcome of a one possession game. In fact, there are almost too many such plays to choose from in the BK era:{' '} <StyledExternalLink href="https://www.youtube.com/watch?v=y0htsUV9L3o"> the deep bomb </StyledExternalLink>{' '} to Will Fuller for a win over Virginia,{' '} <StyledExternalLink href="https://www.youtube.com/watch?v=u5t-t_bZY_Q"> the untimely fumble </StyledExternalLink>{' '} by Cam McDaniel while running out the clock against Northwestern,{' '} <StyledExternalLink href="https://www.youtube.com/watch?v=mqfIcVzeOQM"> the infamous "pick play" </StyledExternalLink>{' '} in a heartbreaking loss to Florida State,{' '} <StyledExternalLink href="https://www.youtube.com/watch?v=mv7s2UAwdao"> the wild overtime affair </StyledExternalLink>{' '} against Pitt. Given the sheer craziness of college football, it is unsurprising that Kelly's win percentage in such contests is only 57.1%, a full 11.1% worse than his overall win percentage. </P> <StatsWrapper> <Stat> <p>Overall Win %</p> <p>68.2%</p> </Stat> <Stat> <p>Win % In One Possession Games</p> <p>57.1%</p> </Stat> </StatsWrapper> <P> If you ignore the 2016 season, Kelly actually has a more respectable 65.9% win percentage in one possession games. And while that may seem fairly close to his overall win percentage, that figure itself rises to 72.6% if we discard that same 2016 season. But as much as we Irish fans would like to wipe that season from our collective memories, we all experienced it and will not soon forget it. </P> <BarChart data={data.nd.brianKellyEra.onePossesssionGameWinPercentages} yMax={100} xAxisLabel="Season" formatCount={(d) => `${d}%`} yAxisLabel="Win % In One Possession Games" xAxisTickLabels={['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']} /> <Caption> Brian Kelly's yearly win percentage in one possession games has been all over the board. </Caption> <P> These figures appear to provide some support that Kelly plays in a lot of one possession games, but we really need to compare them in a broader context. </P> <SectionTitle>Compared To Past Irish Head Coaches</SectionTitle> <P> The first place we can look is to compare how Kelly stacks up against other men who have held the same position as Notre Dame head coach. Over the course of Notre Dame football history, 22 men have coached the Irish in ten or more contests. Here is what they look like ranked according to what percentage of their games were decided by one possession. </P> <Table headers={[ 'Head Coach', 'Seasons Coached', 'National Titles', 'Games Coached', '% One Possession Games', ]} rows={data.coaches.rows} highlightedRowIndexes={[18]} /> <Caption> Brian Kelly plays in a lot more one possession games than the Irish head coaching legends. </Caption> <Note> Although the two point conversion was only adopted by college football in 1958, an 8 point differential was used for all calculations above. If anything, correcting the percentages for older coaches would just make Kelly's number look worse in comparison. </Note> <P> Kelly clearly ends up on the wrong end of this chart, far from his peers who have brought Notre Dame to the promised land of a National Championship and instead smack dab in the middle of Irish coaching failures from the past few decades. And before you say your thanks for him being better than Ty, I'd like to point out that Willingham sported a hefty 13-6 record (68.4%) in one possession games. But this is due to his team sneaking out close games against inferior opponents while getting clobbered en route to an 8-9 record in all other contests. </P> <P> This seems to be another indication that there is something behind this line of criticism against Kelly, but maybe it is unfair to compare this metric over time. After all, the game evolves and maybe there are more close games now than there used to be. So let's look at how Kelly compares against his contemporaries. </P> <SectionTitle>Compared To Other Top 25 Teams</SectionTitle> <P> To get an idea of how Kelly's numbers measure up against other modern coaches, we can look at every team who has finished in the top 25 during his nine season tenure. There are 71 such teams on that list, starting with the final rankings of the 2010 season and including this week's top 25 (welcome to the party Kentucky!). Before we see the whole list, let's first look at the top 15 teams sorted in ascending order of the percentage of games they have played over the past nine seasons which were decided by just one possession: </P> <Table headers={['Team', 'Top 25 Finishes', 'National Titles', '% One Poss Games']} rows={_.take(data.top25.rows, 15)} /> <Caption> Alabama and their four National Champtionships top the list of teams who have played in the lowest percentage of one possession games during Brian Kelly's tenure at Notre Dame. </Caption> <P> No one who follows college football will be surprised to see Alabama on top of this list. They have four National Championships over this period - as many as all other teams combined - as their reward. But there are some surprises, such as Western Michigan and Southern Mississippi, who make this list despite having only a single top 25 finish each. Taking Southern Mississippi as an example, their low percentage is due in large part to only playing in a handful of one possession games during an awful stretch spanning the 2012-14 seasons in which they went a combined 4-32. Their inclusion shows that this metric is by no means a perfect way to determine if a team is good or bad. You can play a low percentage of one possession games and still have little success as a program because you consistently lose by large margins. But make no mistake, teams like Oregon, Alabama, and Boise State sit atop this list because they are consistently beating teams handily, not because they are getting blown out. </P> <P> So where does Notre Dame fit into this list? Let's expand it to include all 71 of the top 25 teams from the past nine seasons and get scrolling. </P> <Table headers={['Team', 'Top 25 Finishes', 'National Titles', '% One Poss Games']} rows={data.top25.rows} highlightedRowIndexes={[70]} /> <Caption> Brian Kelly's Notre Dame has played in a higher percentage of one possession games over the past nine seasons than any other top 25 team. </Caption> <P> Dead. Last. 71 out of 71. Notre Dame has played in a higher percentage of one possession games than any other top 25 team over the past nine seasons. No wonder life has felt so stressful! Over the course of a single season, Notre Dame plays on average over 3 more one possession games than the Crimson Tide. As with Southern Mississippi, this stat can be a bit misleading. Many teams on this list would likely trade places with the varied success Notre Dame has had under Kelly. But this is yet another piece of evidence that Kelly plays in more than his fair share of close games. </P> <SectionTitle>Too Close For Comfort</SectionTitle> <P> These numbers do not prove that Brian Kelly is a bad coach. They only tangentially even touch on Notre Dame's wins and losses under his leadership. But they do lay out some compelling evidence that the criticisms against him regarding playing down to opponents have some statistical backing. When looking at how many one possession games his team has played in, Kelly is nowhere near his top head coaching contemporaries nor his Notre Dame head coaching predecessors. </P> <P> Playing in close games means you are always in it, but it also means the same thing for the other team. Play in too many and some of them are bound to not go your way. And beyond the direct effect they have on win percentage, the second order detrimental effects they have on starters over the course of a season cannot be discounted. Notre Dame has not done especially well these past few Novembers, after all, and this may be one of many contributing factors. </P> <P> Brian Kelly has had his share of success at Notre Dame and the team may just be poised to do something special this season. But the number of one possession games Notre Dame has played in during his tenure is a troubling trend that has continued into this season. It's unclear if Kelly will vanquish a{' '} <StyledExternalLink href="/2018/5">David Shaw-led Stanford team</StyledExternalLink> who has had his number these past few seasons, but it is safe to assume this weekend's matchup will once again come down to the final drive. </P> <Divider /> <NewsletterSignupForm /> </Wrapper> ); };
imports/ui/pages/Documents.js
themeteorchef/base
import React from 'react'; import { Link } from 'react-router'; import { Row, Col, Button } from 'react-bootstrap'; import DocumentsList from '../components/DocumentsList'; const Documents = () => ( <div className="Documents"> <Row> <Col xs={ 12 }> <div className="page-header clearfix"> <h4 className="pull-left">Documents</h4> <Link to="/documents/new"> <Button bsStyle="success" className="pull-right" >New Document</Button> </Link> </div> <DocumentsList /> </Col> </Row> </div> ); export default Documents;
src/core/display/App/Navigation/Horizontal/CategoryNavigation.js
JulienPradet/pigment-store
import React from 'react' import {Match, Miss, Link} from 'react-router' import {Container, Item} from '../../util/View/HorizontalList' import ComponentNavigation from './ComponentNavigation' import ChildrenLinks from './ChildrenLinks' const extractCategoryChildren = (prefix, category) => [ ...category.categories.map((category) => ({ pattern: `${prefix}/category-${category.name}`, name: category.name, render: ({pathname}) => <CategoryNavigation prefix={pathname} parentPathname={prefix} category={category} /> })), ...category.components.map((component) => ({ pattern: `${prefix}/component-${component.name}`, name: component.name, render: ({pathname}) => <ComponentNavigation prefix={pathname} parentPathname={prefix} component={component} /> })) ] const CategoryNavigation = ({category, prefix, parentPathname}) => ( <Container> <Item> <Link to={parentPathname}>{category.name}</Link> </Item> {extractCategoryChildren(prefix, category).map(({pattern, render}) => ( <Match key={pattern} pattern={pattern} render={(...args) => <Item>{render(...args)}</Item>} /> ))} <Miss render={() => ( <Item> <ChildrenLinks children={extractCategoryChildren(prefix, category)} /> </Item> )} /> </Container> ) export default CategoryNavigation
src/components/items_and_income_screen/items_and_income_screen.js
amybingzhao/savings-planner-web
import React, { Component } from 'react'; import Greeting from '../greeting'; import InfoTable from './info_table'; class ItemsAndIncomeScreen extends Component { constructor(props) { super(props); } render() { return ( <div> <Greeting text="Here's your current info:" /> <div className="container"> <div className="col-md-6"> <InfoTable /> </div> <div className="col-md-6"> <InfoTable /> </div> </div> </div> ) } } export default ItemsAndIncomeScreen;
js/jqwidgets/demos/react/app/treegrid/virtualmodewithajax/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxTreeGrid from '../../../jqwidgets-react/react_jqxtreegrid.js'; class App extends React.Component { render() { let source = { dataType: 'json', dataFields: [ { name: 'EmployeeID', type: 'number' }, { name: 'ReportsTo', type: 'number' }, { name: 'FirstName', type: 'string' }, { name: 'LastName', type: 'string' }, { name: 'Country', type: 'string' }, { name: 'City', type: 'string' }, { name: 'Address', type: 'string' }, { name: 'Title', type: 'string' }, { name: 'HireDate', type: 'date' }, { name: 'BirthDate', type: 'date' } ], timeout: 10000, hierarchy: { keyDataField: { name: 'EmployeeID' }, parentDataField: { name: 'ReportsTo' } }, id: 'EmployeeID', root: 'value', url: 'http://services.odata.org/V3/Northwind/Northwind.svc/Employees?$format=json&$callback=?' }; let virtualModeCreateRecords = (expandedRecord, done) => { let dataAdapter = new $.jqx.dataAdapter(source, { formatData: (data) => { if (expandedRecord == null) { data.$filter = '(ReportsTo eq null)' } else { data.$filter = '(ReportsTo eq ' + expandedRecord.EmployeeID + ')' } return data; }, loadComplete: () => { done(dataAdapter.records); }, loadError: (xhr, status, error) => { done(false); throw new Error('http://services.odata.org: ' + error.toString()); } } ); dataAdapter.dataBind(); }; let virtualModeRecordCreating = (record) => { // record is creating. }; let columns = [ { text: 'FirstName', columnGroup: 'Name', dataField: 'FirstName', width: 150 }, { text: 'LastName', columnGroup: 'Name', dataField: 'LastName', width: 150 }, { text: 'Title', dataField: 'Title', width: 200 }, { text: 'Birth Date', dataField: 'BirthDate', cellsFormat: 'd' } ]; return ( <div> <h3 style={{ fontSize: 16, fontFamily: 'Verdana' }}>Data Source: 'http://services.odata.org'</h3> <JqxTreeGrid width={800} columns={columns} virtualModeCreateRecords={virtualModeCreateRecords} virtualModeRecordCreating={virtualModeRecordCreating} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/containers/editor/RepoEditor/SearchMan.js
mydearxym/mastani
import React from 'react' import { ISSUE_ADDR } from '@/config' import { buildLog } from '@/utils/logger' import SearchInputer from './SearchInputer' import TokenSetter from './TokenSetter' import { Wrapper, SearchTitle, FormWrapper, Letter, Footer, SetTokenWrapper, SetTokenIssue, } from './styles/search_man' import { changeSubView } from './logic' /* eslint-disable-next-line */ const log = buildLog('C:RepoEditor') const SearchMan = ({ value, searching, subView, tokenValue }) => ( <Wrapper> <FormWrapper> <SearchTitle> <Letter color="#2D85EF">G</Letter> <Letter color="#F3423D">i</Letter> <Letter color="#FFBC35">t</Letter> <Letter color="#2D85EF">h</Letter> <Letter color="#10A859">u</Letter> <Letter color="#F3423D">b</Letter> </SearchTitle> {subView === 'search' ? ( <SearchInputer value={value} searhing={searching} /> ) : ( <TokenSetter value={tokenValue} /> )} </FormWrapper> <Footer> 若有问题请尝试 <SetTokenWrapper onClick={changeSubView('token')}> 重新设置token </SetTokenWrapper> 或{' '} <SetTokenIssue href={`${ISSUE_ADDR}/323`} rel="noopener noreferrer" target="_blank" > 报告issue </SetTokenIssue> </Footer> </Wrapper> ) export default React.memo(SearchMan)
node_modules/react-bootstrap/es/Jumbotron.js
vietvd88/developer-crawler
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Jumbotron = function (_React$Component) { _inherits(Jumbotron, _React$Component); function Jumbotron() { _classCallCheck(this, Jumbotron); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Jumbotron.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Jumbotron; }(React.Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; export default bsClass('jumbotron', Jumbotron);
example/src/pages/ActivationByTap.js
ethanselzer/react-cursor-position
import React, { Component } from 'react'; import { Link } from 'react-router'; import { Col, Grid, Jumbotron, Row } from 'react-bootstrap'; import Helmet from 'react-helmet'; import Header from '../components/Header'; import ActivationByTap from '../components/ActivationByTap'; import 'bootstrap/dist/css/bootstrap.css'; import '../styles/app.css'; export default class extends Component { render() { return ( <div> <Helmet title="Class Name | React Cursor Position" /> <Header {...this.props}/> <Jumbotron> <Grid> <Row> <Col sm={12}> <h2>Tap to Activate - Example</h2> </Col> </Row> <Row> <Col sm={5}> <ul className="summary__list"> <li> Interaction: Tap to activate. Tap again to deactivate </li> <li> Assign a number to tapDurationInMs and or tapMoveThreshold props, to control the behavior of the tap </li> <li> See Related:&nbsp; <Link to="activate-by-press"> Activate by Press </Link> ,&nbsp; <Link to="activate-by-touch"> Activate by Touch </Link>,&nbsp; <Link to="activate-by-click"> Activate by Click </Link>,&nbsp; <Link to="activate-by-hover"> Activate by Hover </Link> </li> </ul> </Col> <Col sm={5}> <ul className="summary__list"> <li>Prop: activationInteractionTouch</li> <li>Type: One of [INTERACTIONS.PRESS, INTERACTIONS.TAP, INTERACTIONS.TOUCH]</li> <li>Default: INTERACTIONS.PRESS</li> <li>Import INTERACTIONS from react-cursor-position (see code example below)</li> <li> <a href="https://github.com/ethanselzer/react-cursor-position/blob/master/example/src/components/ActivationByTap.js"> Example Code on GitHub </a> </li> </ul> </Col> </Row> </Grid> </Jumbotron> <Grid> <Row> <Col sm={6} md={4}> <ActivationByTap /> </Col> <Col sm={6} md={8} className="example__source-container" style={{ height: '270px' }} > <iframe title="example" src="activation-tap.html" frameBorder="0" className="code-frame" /> </Col> </Row> </Grid> </div> ); } }
examples/react-pokedex/src/index.js
dawee/dispersive
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
Js/Ui/Components/ClickSuccess/index.js
Webiny/Webiny
import React from 'react'; import _ from 'lodash'; import Webiny from 'webiny'; class ClickSuccess extends Webiny.Ui.Component { constructor(props) { super(props); this.state = {data: {}}; this.bindMethods('getContent,onClick,hide'); } hide() { return this.dialog.hide(); } onClick() { return Promise.resolve(this.realOnClick(this)).then(() => { return this.dialog.show(); }); } getContent() { const content = this.props.children; if (_.isFunction(content)) { return content({ success: ({data}) => { this.setState({data}, () => this.dialog.show()); } }); } const input = React.Children.toArray(content)[0]; this.realOnClick = input.props.onClick; const props = _.omit(input.props, ['onClick']); props.onClick = this.onClick; return React.cloneElement(input, props); } } ClickSuccess.defaultProps = { onClose: _.noop, message: null, renderDialog: null, renderer() { const dialogProps = { ref: ref => this.dialog = ref, message: () => _.isFunction(this.props.message) ? this.props.message(this.state.data) : this.props.message, onClose: () => { this.hide().then(this.props.onClose); } }; if (_.isFunction(this.props.renderDialog)) { dialogProps['renderDialog'] = this.props.renderDialog.bind(this, {data: this.state.data, close: dialogProps.onClose}); } const {Modal} = this.props; return ( <webiny-click-success> {this.getContent()} <Modal.Success {...dialogProps}/> </webiny-click-success> ); } }; export default Webiny.createComponent(ClickSuccess, {modules: ['Modal']});
examples/shared-root/app.js
cojennin/react-router
import React from 'react'; import { Router, Route, Link } from 'react-router'; var App = React.createClass({ render() { return ( <div> <p> This illustrates how routes can share UI w/o sharing the URL. When routes have no path, they never match themselves but their children can, allowing "/signin" and "/forgot-password" to both be render in the <code>SignedOut</code> component. </p> <ol> <li><Link to="/home">Home</Link></li> <li><Link to="/signin">Sign in</Link></li> <li><Link to="/forgot-password">Forgot Password</Link></li> </ol> {this.props.children} </div> ); } }); var SignedIn = React.createClass({ render() { return ( <div> <h2>Signed In</h2> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return ( <h3>Welcome home!</h3> ); } }); var SignedOut = React.createClass({ render() { return ( <div> <h2>Signed Out</h2> {this.props.children} </div> ); } }); var SignIn = React.createClass({ render() { return ( <h3>Please sign in.</h3> ); } }); var ForgotPassword = React.createClass({ render() { return ( <h3>Forgot your password?</h3> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route component={SignedOut}> <Route path="signin" component={SignIn} /> <Route path="forgot-password" component={ForgotPassword} /> </Route> <Route component={SignedIn}> <Route path="home" component={Home} /> </Route> </Route> </Router> ), document.getElementById('example'));
src/routes.js
kpuno/survey-app
import React from 'react'; import { Route } from 'react-router'; import App from './components/App'; import HomePage from './components/HomePage'; import NotFoundPage from './components/NotFoundPage'; import SignIn from './components/auth/SignIn'; import SignUp from './components/auth/SignUp'; import EditProfile from './components/user/EditProfile'; import RequireAuth from './components/hocs/requireAuth'; import CreateSurvey from './components/survey/CreateSurvey'; import Dashboard from './components/Dashboard'; import Survey from './components/survey/Survey'; import SearchSurvey from './components/survey/SearchSurvey'; import Analytics from './components/survey/Analytics'; import SurveyStats from './components/survey/SurveyStats'; import Exipred from './components/survey/Exipred'; import Settings from './components/Settings'; import ChangePassword from './components/user/ChangePassword'; export default ( <Route path="/" component={App}> <Route path="/home" component={HomePage} /> <Route path="/signin" component={SignIn} /> <Route path="/signup" component={SignUp} /> <Route path="/dashboard" component={RequireAuth(Dashboard)} /> <Route path="/editprofile" component={RequireAuth(EditProfile)} /> <Route path="/changepassword" component={RequireAuth(ChangePassword)} /> <Route path="/createsurvey" component={RequireAuth(CreateSurvey)} /> <Route path="/survey" component={Survey} /> <Route path="/searchsurvey" component={SearchSurvey} /> <Route path="/surveyexipred" component={Exipred} /> <Route path="/analytics" component={RequireAuth(Analytics)} /> <Route path="/analytics/:title" component={RequireAuth(SurveyStats)} /> <Route path="/settings" component={RequireAuth(Settings)} /> <Route path="*" component={NotFoundPage} /> </Route> );
examples/auth-flow/app.js
rubengrill/react-router
import React from 'react' import { render } from 'react-dom' import { Router, Route, Link, History } from 'react-router' import { createHistory, useBasename } from 'history' import auth from './auth' const history = useBasename(createHistory)({ basename: '/auth-flow' }) const App = React.createClass({ getInitialState() { return { loggedIn: auth.loggedIn() } }, updateAuth(loggedIn) { this.setState({ loggedIn: loggedIn }) }, componentWillMount() { auth.onChange = this.updateAuth auth.login() }, render() { return ( <div> <ul> <li> {this.state.loggedIn ? ( <Link to="/logout">Log out</Link> ) : ( <Link to="/login">Sign in</Link> )} </li> <li><Link to="/about">About</Link></li> <li><Link to="/dashboard">Dashboard</Link> (authenticated)</li> </ul> {this.props.children} </div> ) } }) const Dashboard = React.createClass({ render() { const token = auth.getToken() return ( <div> <h1>Dashboard</h1> <p>You made it!</p> <p>{token}</p> </div> ) } }) const Login = React.createClass({ mixins: [ History ], getInitialState() { return { error: false } }, handleSubmit(event) { event.preventDefault() const email = this.refs.email.value const pass = this.refs.pass.value auth.login(email, pass, (loggedIn) => { if (!loggedIn) return this.setState({ error: true }) const { location } = this.props if (location.state && location.state.nextPathname) { this.history.replaceState(null, location.state.nextPathname) } else { this.history.replaceState(null, '/') } }) }, render() { return ( <form onSubmit={this.handleSubmit}> <label><input ref="email" placeholder="email" defaultValue="joe@example.com" /></label> <label><input ref="pass" placeholder="password" /></label> (hint: password1)<br /> <button type="submit">login</button> {this.state.error && ( <p>Bad login information</p> )} </form> ) } }) const About = React.createClass({ render() { return <h1>About</h1> } }) const Logout = React.createClass({ componentDidMount() { auth.logout() }, render() { return <p>You are now logged out</p> } }) function requireAuth(nextState, replaceState) { if (!auth.loggedIn()) replaceState({ nextPathname: nextState.location.pathname }, '/login') } render(( <Router history={history}> <Route path="/" component={App}> <Route path="login" component={Login} /> <Route path="logout" component={Logout} /> <Route path="about" component={About} /> <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> </Route> </Router> ), document.getElementById('example'))
stories/examples/BadgeVariations.js
reactstrap/reactstrap
import React from 'react'; import { Badge } from 'reactstrap'; const Example = (props) => { return ( <div> <Badge color="primary">Primary</Badge> <Badge color="secondary">Secondary</Badge> <Badge color="success">Success</Badge> <Badge color="danger">Danger</Badge> <Badge color="warning">Warning</Badge> <Badge color="info">Info</Badge> <Badge color="light">Light</Badge> <Badge color="dark">Dark</Badge> </div> ); } export default Example;
packages/material-ui-icons/src/Train.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Train = props => <SvgIcon {...props}> <path d="M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-7H6V6h5v4zm2 0V6h5v4h-5zm3.5 7c-.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.5z" /> </SvgIcon>; Train = pure(Train); Train.muiName = 'SvgIcon'; export default Train;
public/js/components/SubmitButton.js
davejtoews/cfl-power-rankings
import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; module.exports = class extends React.Component { static contextTypes = { feathersApp: PropTypes.object, login: PropTypes.bool }; state = { submission: { user: this.props.userId, ranks: [], week: '', blurb: '' }, submitted: this.props.submitted, waiting: false }; componentWillReceiveProps(nextProps) { this.setState({ submission: { user: this.props.userId, ranks: this.getRankList(nextProps.rankedTeams), week: nextProps.weekId, blurb: nextProps.blurb }, submitted: nextProps.submitted }); } setWaiting = (waiting) => { this.setState({ waiting: waiting }); }; getRankList = (rankedTeams) => { return rankedTeams.map(function(team) { return team._id; }); }; handleClick = (e) => { e.preventDefault(); var setSubmitted = this.props.setSubmitted; var setNotifications = this.props.setNotifications; var setWaiting = this.setWaiting; if ( !this.state.waiting && this.context.login && this.state.submission.ranks.length && this.state.submission.week ) { setWaiting(true); if (this.state.submitted) { this.context.feathersApp.service('rankings').patch(this.state.submitted, this.state.submission).then(function(result){ setNotifications('success', 'Rankings updated.'); setWaiting(false); }).catch(function(error){ console.error('Problem updating rankings!', error); setNotifications('error', 'Problem updating rankings. ' + error); setWaiting(false); }); } else { this.context.feathersApp.service('rankings').create(this.state.submission).then(function(result){ setSubmitted(result._id); setNotifications('success', 'Rankings submitted.'); setWaiting(false); }).catch(function(error){ console.error('Problem submitting rankings!', error); setNotifications('error', 'Problem submitting rankings. ' + error); setWaiting(false); }); } } }; render() { var text = (this.state.submitted) ? 'Update' : 'Submit'; var disabled = (this.state.waiting) ? 'disabled' : ''; var buttonClasses = classNames('button ' + disabled); return( <a href="#" className={ buttonClasses } onClick={ this.handleClick }>{text}</a> ); } };
client/src/components/PollChart.js
juandaco/voting-app
import React from 'react'; import { CardTitle } from 'react-mdl'; import { Doughnut } from 'react-chartjs-2'; const PollChart = ({ pollTitle, chartData }) => { return ( <CardTitle expand style={{ color: '#000', marginTop: -40, }} > <div style={{ marginLeft: -5, }} > <h4 style={{ marginLeft: 10 }}>{pollTitle}</h4> <Doughnut data={chartData} height={260} width={260} options={{ animation: false, // for Mobile??? */ }} /> </div> </CardTitle> ); }; export default PollChart;
src/components/theme-giraffe/signature-list-pagination.js
MoveOnOrg/mop-frontend
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' export const PreviousButton = ({ onClick, visible }) => ( <button onClick={onClick} className={cx('mo-btn', { hidden: !visible })} > Previous </button> ) PreviousButton.propTypes = { onClick: PropTypes.func, visible: PropTypes.bool } export const NextButton = ({ onClick, visible }) => ( <button onClick={onClick} className={cx('mo-btn', { hidden: !visible })} > Next </button> ) NextButton.propTypes = { onClick: PropTypes.func, visible: PropTypes.bool } export const Pager = ({ previousButton, nextButton }) => ( <div className='petition-details__comments__pagination'> {previousButton} {nextButton} </div> ) Pager.propTypes = { previousButton: PropTypes.node, nextButton: PropTypes.node }
modules/TransitionHook.js
dashed/react-router
import React from 'react'; import warning from 'warning'; var { object } = React.PropTypes; var TransitionHook = { contextTypes: { router: object.isRequired }, componentDidMount() { warning( typeof this.routerWillLeave === 'function', 'Components that mixin TransitionHook should have a routerWillLeave method, check %s', this.constructor.displayName || this.constructor.name ); if (this.routerWillLeave) this.context.router.addTransitionHook(this.routerWillLeave); }, componentWillUnmount() { if (this.routerWillLeave) this.context.router.removeTransitionHook(this.routerWillLeave); } }; export default TransitionHook;
src/mui/field/ReferenceManyField.js
azureReact/AzureReact
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import LinearProgress from 'material-ui/LinearProgress'; import { crudGetManyReference as crudGetManyReferenceAction } from '../../actions/dataActions'; import { getIds, getReferences, nameRelatedTo, } from '../../reducer/admin/references/oneToMany'; import { SORT_ASC, SORT_DESC, } from '../../reducer/admin/resource/list/queryReducer'; /** * Render related records to the current one. * * You must define the fields to be passed to the iterator component as children. * * @example Display all the comments of the current post as a datagrid * <ReferenceManyField reference="comments" target="post_id"> * <Datagrid> * <TextField source="id" /> * <TextField source="body" /> * <DateField source="created_at" /> * <EditButton /> * </Datagrid> * </ReferenceManyField> * * @example Display all the books by the current author, only the title * <ReferenceManyField reference="books" target="author_id"> * <SingleFieldList> * <ChipField source="title" /> * </SingleFieldList> * </ReferenceManyField> * * By default, restricts the possible values to 25. You can extend this limit * by setting the `perPage` prop. * * @example * <ReferenceManyField perPage={10} reference="comments" target="post_id"> * ... * </ReferenceManyField> * * By default, orders the possible values by id desc. You can change this order * by setting the `sort` prop (an object with `field` and `order` properties). * * @example * <ReferenceManyField sort={{ field: 'created_at', order: 'DESC' }} reference="comments" target="post_id"> * ... * </ReferenceManyField> * * Also, you can filter the query used to populate the possible values. Use the * `filter` prop for that. * * @example * <ReferenceManyField filter={{ is_published: true }} reference="comments" target="post_id"> * ... * </ReferenceManyField> */ export class ReferenceManyField extends Component { constructor(props) { super(props); this.state = { sort: props.sort }; } componentDidMount() { this.fetchReferences(); } componentWillReceiveProps(nextProps) { if (this.props.record.id !== nextProps.record.id) { this.fetchReferences(nextProps); } } setSort = field => { const order = this.state.sort.field === field && this.state.sort.order === SORT_ASC ? SORT_DESC : SORT_ASC; this.setState({ sort: { field, order } }, this.fetchReferences); }; fetchReferences( { reference, record, resource, target, perPage, filter } = this.props ) { const { crudGetManyReference } = this.props; const pagination = { page: 1, perPage }; const relatedTo = nameRelatedTo( reference, record.id, resource, target, filter ); crudGetManyReference( reference, target, record.id, relatedTo, pagination, this.state.sort, filter ); } render() { const { resource, reference, data, ids, children, basePath, isLoading, } = this.props; if (React.Children.count(children) !== 1) { throw new Error( '<ReferenceManyField> only accepts a single child (like <Datagrid>)' ); } if (typeof ids === 'undefined') { return <LinearProgress style={{ marginTop: '1em' }} />; } const referenceBasePath = basePath.replace(resource, reference); // FIXME obviously very weak return React.cloneElement(children, { resource: reference, ids, data, isLoading, basePath: referenceBasePath, currentSort: this.state.sort, setSort: this.setSort, }); } } ReferenceManyField.propTypes = { addLabel: PropTypes.bool, basePath: PropTypes.string.isRequired, children: PropTypes.element.isRequired, crudGetManyReference: PropTypes.func.isRequired, filter: PropTypes.object, ids: PropTypes.array, label: PropTypes.string, perPage: PropTypes.number, record: PropTypes.object, reference: PropTypes.string.isRequired, data: PropTypes.object, resource: PropTypes.string.isRequired, sort: PropTypes.shape({ field: PropTypes.string, order: PropTypes.oneOf(['ASC', 'DESC']), }), source: PropTypes.string.isRequired, target: PropTypes.string.isRequired, isLoading: PropTypes.bool, }; ReferenceManyField.defaultProps = { filter: {}, perPage: 25, sort: { field: 'id', order: 'DESC' }, source: '', }; function mapStateToProps(state, props) { const relatedTo = nameRelatedTo( props.reference, props.record.id, props.resource, props.target, props.filter ); return { data: getReferences(state, props.reference, relatedTo), ids: getIds(state, relatedTo), isLoading: state.admin.loading > 0, }; } const ConnectedReferenceManyField = connect(mapStateToProps, { crudGetManyReference: crudGetManyReferenceAction, })(ReferenceManyField); ConnectedReferenceManyField.defaultProps = { addLabel: true, source: '', }; export default ConnectedReferenceManyField;
src/main/js/element/ConsoleSelect.js
MannanM/corporate-game-share
import React, { Component } from 'react'; import { FormControl } from 'react-bootstrap'; import { GetConsoles } from '../Client'; class ConsoleSelect extends Component { componentDidMount() { GetConsoles().then((result) => { this.setState({ consoles: result.data }); }); } render() { let options = <></>; if (this.state && this.state.consoles) { options = this.state.consoles.map((c) => <option key={c.id} value={c.attributes.shortName}> {c.attributes.name} </option>); } return <FormControl componentClass="select" placeholder="select" {...this.props} > <option value="">Please select...</option> {options} </FormControl> } } export default ConsoleSelect;
src/components/calendar/content/layout/days.js
vFujin/HearthLounge
import React from 'react'; import dateFns from "date-fns"; import PropTypes from 'prop-types'; const CalendarDays = ({currentMonth, mobileBreakpoint}) => { const dateFormat = window.innerWidth <= mobileBreakpoint ? "ddd" : "dddd"; const days = []; let startDate = dateFns.startOfWeek(currentMonth); for (let i = 0; i < 7; i++) { days.push( <div className="calendar__col calendar__col--center" key={i}> {dateFns.format(dateFns.addDays(startDate, i), dateFormat)} </div> ); } return <div className="calendar__days calendar__row">{days}</div>; }; CalendarDays.propTypes = { currentMonth: PropTypes.instanceOf(Date).isRequired }; export default CalendarDays;
src/components/Header.js
Morrisai/cppeiCalculator
import React from 'react'; import Typography from '@material-ui/core/Typography'; import { withStyles } from '@material-ui/core/styles'; import { Button, Paper } from '@material-ui/core'; import Model from '../model/model'; const styles = theme => ({ root: { background: theme.palette.primary.main, padding:'2rem', textAlign:'center', "@media (max-width:500px)": { padding:'1rem', } }, button:{ textAlign:'center', margin: '0 0 1rem 0', }, text:{ color: theme.palette.primary.contrastText, maxWidth:'75%', margin: '1rem auto', "@media (max-width:500px)": { maxWidth:'100%', } }, h1:{ color: theme.palette.primary.contrastText, padding:'2rem 0rem', maxWidth:'75%', margin: 'auto', "@media (max-width:500px)": { maxWidth:'100%', fontSize:'2rem' } } }); const format = new Intl.NumberFormat().format; class Header extends React.Component { render () { const { classes } = this.props; return ( <Paper className={classes.root}> <Typography variant="display3" gutterBottom className={classes.h1}> When will I max out my CPP and EI contributions? </Typography> <Button className={classes.button} size="small" variant="contained" href="#calculator"> Skip to calculator </Button> <div > <Typography gutterBottom className={classes.text}>Have you ever wondered why part way through the year all of a sudden you stop paying EI and CPP premiums on each paycheque and instead just get to pocket that money? For some people it happens very early in the year and for some people it might happen near the end or not at all. Once you max out, you simply stop paying for those extra deductions and your pay cheque gets a nice little bump. </Typography> <Typography gutterBottom className={classes.text}>The Canadian government has set maximums on how much an invidual can contribute to the CPP (Canadian Pension Plan) and to EI (Employment Insurance). Once you have reached the maximum contribution for the year you will see an increase on your net pay going forward as these deductions will no longer be applied. </Typography> <Typography gutterBottom className={classes.text}> For CPP, with few exceptions, every person over the age of 18, who works in Canada outside of Quebec and earns more than a minimum amount ($3,500 per year) must contribute to CPP. In {Model.year}, the maximum amount for CPP is ${format(Model.cppMaxEarning)} </Typography> <Typography gutterBottom className={classes.text}> Employment Insurance (EI) provides temporary financial assistance to unemployed Canadians who have lost their job through no fault of their own, while they look for work or upgrade their skills. The maximum insurable earnings for EI for {Model.year} is ${format(Model.eiMaxEarning)}. </Typography> <Typography variant="body2" gutterBottom className={classes.text}> Use the calculator below to estimate the date that you will max out your CPP and EI payments in {Model.year}. </Typography> </div> </Paper> ) } } export default withStyles(styles)(Header);
src/components/metadata/statics/StaticMetaArray.js
jekyll/jekyll-admin
import React from 'react'; import PropTypes from 'prop-types'; import StaticMetaArrayItem from './StaticMetaArrayItem'; import { computeFieldType } from '../../../utils/metadata'; export default function StaticMetaArray({ fieldValue }) { const items = fieldValue.map((item, i) => { const type = computeFieldType(item); return ( <StaticMetaArrayItem key={i} index={i} fieldValue={item} type={type} /> ); }); return <div className="meta-value-array">{items}</div>; } StaticMetaArray.propTypes = { fieldValue: PropTypes.any.isRequired, };
pkg/users/password-dialogs.js
moraleslazaro/cockpit
/* * This file is part of Cockpit. * * Copyright (C) 2020 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import cockpit from 'cockpit'; import React from 'react'; import { superuser } from "superuser"; import { Modal } from 'patternfly-react'; import { Validated, has_errors } from "./dialog-utils.js"; import { show_modal_dialog } from "cockpit-components-dialog.jsx"; const _ = cockpit.gettext; function passwd_self(old_pass, new_pass) { var old_exps = [ /Current password: $/, /.*\(current\) UNIX password: $/, ]; var new_exps = [ /.*New password: $/, /.*Retype new password: $/, /.*Enter new \w*\s?password: $/, /.*Retype new \w*\s?password: $/ ]; var bad_exps = [ /.*BAD PASSWORD:.*/ ]; var too_new_exps = [ /.*must wait longer to change.*/ ]; return new Promise((resolve, reject) => { var buffer = ""; var sent_new = false; var failure = _("Old password not accepted"); var i; var proc; var timeout = window.setTimeout(function() { failure = _("Prompting via passwd timed out"); proc.close("terminated"); }, 10 * 1000); proc = cockpit.spawn(["/usr/bin/passwd"], { pty: true, environ: ["LC_ALL=C"], err: "out" }) .always(function() { window.clearInterval(timeout); }) .done(function() { resolve(); }) .fail(function(ex) { if (ex.exit_status) ex = new Error(failure); reject(ex); }) .stream(function(data) { buffer += data; for (i = 0; i < old_exps.length; i++) { if (old_exps[i].test(buffer)) { buffer = ""; this.input(old_pass + "\n", true); return; } } for (i = 0; i < too_new_exps.length; i++) { if (too_new_exps[i].test(buffer)) { buffer = ""; failure = _("You must wait longer to change your password"); this.input("\n", true); return; } } for (i = 0; i < new_exps.length; i++) { if (new_exps[i].test(buffer)) { buffer = ""; this.input(new_pass + "\n", true); failure = _("Failed to change password"); sent_new = true; return; } } if (sent_new) for (i = 0; i < bad_exps.length; i++) { if (bad_exps[i].test(buffer)) { failure = _("New password was not accepted"); return; } } }); }); } export function passwd_change(user, new_pass) { return new Promise((resolve, reject) => { cockpit.spawn(["chpasswd"], { superuser: "require", err: "out" }) .input(user + ":" + new_pass) .done(function() { resolve(); }) .fail(function(ex, response) { if (ex.exit_status) { console.log(ex); if (response) ex = new Error(response); else ex = new Error(_("Failed to change password")); } reject(ex); }); }); } export function password_quality(password, force) { return new Promise((resolve, reject) => { cockpit.spawn('/usr/bin/pwscore', { err: "message" }) .input(password) .done(function(content) { var quality = parseInt(content, 10); if (quality === 0) { reject(new Error(_("Password is too weak"))); } else if (quality <= 33) { resolve("weak"); } else if (quality <= 66) { resolve("okay"); } else if (quality <= 99) { resolve("good"); } else { resolve("excellent"); } }) .fail(function(ex) { if (!force) reject(new Error(ex.message || _("Password is not acceptable"))); else resolve("weak"); }); }); } function SetPasswordDialogBody({ state, errors, change }) { const { need_old, password_old, password, password_confirm, password_strength, password_message } = state; return ( <Modal.Body> <form className="ct-form"> { need_old && <> <label className="control-label" htmlFor="account-set-password-old">{_("Old password")}</label> <Validated errors={errors} error_key="password_old"> <input className="form-control check-passwords" type="password" id="account-set-password-old" value={password_old} onChange={event => change("password_old", event.target.value)} /> </Validated> </> } <label className="control-label" htmlFor="account-set-password-pw1">{_("New password")}</label> <Validated errors={errors} error_key="password"> <input className="form-control check-passwords" type="password" id="account-set-password-pw1" value={password} onChange={event => change("password", event.target.value)} /> </Validated> <label className="control-label" htmlFor="account-set-password-pw2">{_("Confirm new password")}</label> <div className="check-passwords dialog-wrapper"> <Validated errors={errors} error_key="password_confirm"> <input className="form-control" type="password" id="account-set-password-pw2" value={password_confirm} onChange={event => change("password_confirm", event.target.value)} /> </Validated> <div id="account-set-password-meter" className={"progress password-strength-meter " + password_strength}> <div className="progress-bar" /> <div className="progress-bar" /> <div className="progress-bar" /> <div className="progress-bar" /> </div> <div> <span id="account-set-password-meter-message" className="help-block">{password_message}</span> </div> </div> </form> </Modal.Body> ); } export function set_password_dialog(account, current_user) { let dlg = null; const change_self = (account.name == current_user && !superuser.allowed); const state = { need_old: change_self, password_old: "", password: "", password_confirm: "", password_strength: "", password_message: "", confirm_weak: false, }; let errors = { }; let old_password = null; function change(field, value) { state[field] = value; if (state.password != old_password) { state.confirm_weak = false; old_password = state.password; if (state.password) { password_quality(state.password) .catch(ex => "weak") .then(strength => { state.password_strength = strength; if (strength == "excellent") state.password_message = _("Excellent password"); else state.password_message = ""; update(); }); } else { state.password_strength = ""; state.password_message = ""; } } update(); } function validate(force) { errors = { }; if (state.password != state.password_confirm) errors.password_confirm = _("The passwords do not match"); return password_quality(state.password, force) .catch(ex => { errors.password = (ex.message || ex.toString()).replace("\n", " "); errors.password += "\n" + cockpit.format(_("Click $0 again to use the password anyway."), _("Set")); }) .then(() => { return !has_errors(errors); }); } function update() { const props = { id: "account-set-password-dialog", title: _("Set password"), body: <SetPasswordDialogBody state={state} errors={errors} change={change} /> }; const footer = { actions: [ { caption: _("Set"), style: "primary", clicked: () => { const second_click = state.confirm_weak; state.confirm_weak = !state.confirm_weak; return validate(second_click).then(valid => { if (valid) { if (change_self) return passwd_self(state.password_old, state.password); else return passwd_change(account.name, state.password); } else { update(); return Promise.reject(); } }); } } ] }; if (!dlg) dlg = show_modal_dialog(props, footer); else { dlg.setProps(props); dlg.setFooterProps(footer); } } update(); } export function reset_password_dialog(account) { var msg = cockpit.format(_("The account '$0' will be forced to change their password on next login"), account.name); const props = { id: "password-reset", title: _("Force password change"), body: <Modal.Body><p>{msg}</p></Modal.Body> }; const footer = { actions: [ { caption: _("Reset"), style: "primary", clicked: () => { return cockpit.spawn(["/usr/bin/passwd", "-e", account.name], { superuser : true, err: "message" }); } } ] }; show_modal_dialog(props, footer); }
src/svg-icons/image/add-a-photo.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAddAPhoto = (props) => ( <SvgIcon {...props}> <path d="M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z"/> </SvgIcon> ); ImageAddAPhoto = pure(ImageAddAPhoto); ImageAddAPhoto.displayName = 'ImageAddAPhoto'; ImageAddAPhoto.muiName = 'SvgIcon'; export default ImageAddAPhoto;
public/javascripts/components/banks.js
AlaskanHusky/currency-exchange
import React, { Component } from 'react'; import Menu from './menu'; class Banks extends Component { constructor() { super(); this.state = { banks: [] } } componentDidMount() { const xmlHttp = new XMLHttpRequest(); const vm = this; xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { vm.setState({ banks: JSON.parse(xmlHttp.responseText) }); } }; xmlHttp.open("GET", `/api/banks/`, true); // true for asynchronous xmlHttp.send(null); } renderItems() { return this.state.banks.map(function (bank) { return <li>{bank.bank}</li>; }); } render() { return ( <div> <Menu /> <ul className="list"> {this.renderItems()} </ul> </div> ); } } export default Banks;
js/App/Components/Events/EventsNavigator.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. * */ // @flow 'use strict'; import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import EventsScreenConfigs from './EventsScreenConfigs'; const initialRouteName = 'EventsList'; import { prepareNavigator, shouldNavigatorUpdate, } from '../../Lib/NavigationService'; const NavigatorConfigs = { initialRouteName, initialRouteKey: initialRouteName, headerMode: 'none', cardStyle: { shadowColor: 'transparent', shadowOpacity: 0, elevation: 0, }, }; const Stack = createStackNavigator(); const ScreenConfigs = [ ...EventsScreenConfigs, ]; const EventsNavigator: Object = React.memo<Object>((props: Object): Object => { return prepareNavigator(Stack, {ScreenConfigs, NavigatorConfigs}, props); }, shouldNavigatorUpdate); export default EventsNavigator;
examples/example-1/CustomElementChoose.js
ezypeeze/react-mozer
import React from 'react'; import PropTypes from 'prop-types'; import {ElementHOC} from '../../src'; class CustomElementChoose extends React.Component { static propTypes = { items: PropTypes.arrayOf(String) }; static defaultProps = { items: [] }; render() { return ( <div className="CustomElementChoose"> {this.props.label} <ul> {this.props.items.map((item, i) => ( <li key={i}><a onClick={() => this.props.onChange(item)} onMouseOver={this.props.onTouch}>{item}</a></li> ))} </ul> </div> ); } } export default ElementHOC(CustomElementChoose);
app/components/DetailHeader.js
arixse/ReactNeteaseCloudMusic
import React from 'react'; const DetailHeader = (props) => { return ( <div> <div className="detail-header" style={props.cla}> <span className="iconfont prev" onTouchTap={() => { props.history.goBack(); }}>&#xe622;</span> {props.title} </div> </div> ); }; DetailHeader.propTypes = { history: React.PropTypes.object, title: React.PropTypes.string, cla: React.PropTypes.object }; export default DetailHeader ;
test/focus-first-suggestion-clear-on-enter/AutosuggestApp.js
JacksonKearl/react-autosuggest-ie11-compatible
import React, { Component } from 'react'; import sinon from 'sinon'; import Autosuggest from '../../src/Autosuggest'; import languages from '../plain-list/languages'; import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js'; import { addEvent } from '../helpers'; const getMatchingLanguages = value => { const escapedValue = escapeRegexCharacters(value.trim()); const regex = new RegExp('^' + escapedValue, 'i'); return languages.filter(language => regex.test(language.name)); }; let app = null; export const getSuggestionValue = suggestion => suggestion.name; export const renderSuggestion = suggestion => <span>{suggestion.name}</span>; export const onChange = sinon.spy((event, { newValue }) => { addEvent('onChange'); app.setState({ value: newValue }); }); export const onSuggestionsFetchRequested = ({ value }) => { app.setState({ suggestions: getMatchingLanguages(value) }); }; export const onSuggestionsClearRequested = () => { app.setState({ suggestions: [] }); }; export const onSuggestionSelected = sinon.spy(() => { addEvent('onSuggestionSelected'); app.setState({ value: '' }); }); export default class AutosuggestApp extends Component { constructor() { super(); app = this; this.state = { value: '', suggestions: [] }; } render() { const { value, suggestions } = this.state; const inputProps = { value, onChange }; return ( <Autosuggest suggestions={suggestions.slice()} onSuggestionsFetchRequested={onSuggestionsFetchRequested} onSuggestionsClearRequested={onSuggestionsClearRequested} onSuggestionSelected={onSuggestionSelected} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} highlightFirstSuggestion={true} /> ); } }
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
TimurTarasenko/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react'; const getStateFromStores = (userId) => { const thisPeer = PeerStore.getUserPeer(userId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer) }; }; var UserProfile = React.createClass({ propTypes: { user: React.PropTypes.object.isRequired }, mixins: [PureRenderMixin], getInitialState() { return getStateFromStores(this.props.user.id); }, componentWillMount() { DialogStore.addNotificationsListener(this.whenNotificationChanged); }, componentWillUnmount() { DialogStore.removeNotificationsListener(this.whenNotificationChanged); }, componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.user.id)); }, addToContacts() { ContactActionCreators.addContact(this.props.user.id); }, removeFromContacts() { ContactActionCreators.removeContact(this.props.user.id); }, onNotificationChange(event) { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); }, whenNotificationChanged() { this.setState(getStateFromStores(this.props.user.id)); }, render() { const user = this.props.user; const isNotificationsEnabled = this.state.isNotificationsEnabled; let addToContacts; if (user.isContact === false) { addToContacts = <a className="link__blue" onClick={this.addToContacts}>Add to contacts</a>; } else { addToContacts = <a className="link__red" onClick={this.removeFromContacts}>Remove from contacts</a>; } return ( <div className="activity__body profile"> <div className="profile__name"> <AvatarItem image={user.bigAvatar} placeholder={user.placeholder} size="medium" title={user.name}/> <h3>{user.name}</h3> </div> <div className="notifications"> <label htmlFor="notifications">Enable Notifications</label> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </div> <UserProfileContactInfo phones={user.phones}/> <ul className="profile__list profile__list--usercontrols"> <li className="profile__list__item"> {addToContacts} </li> </ul> </div> ); } }); export default UserProfile;
frontend/src/components/profile/navs.js
1905410/Misago
import React from 'react'; import { Link } from 'react-router'; // jshint ignore:line import Li from 'misago/components/li'; //jshint ignore:line import FollowButton from 'misago/components/profile/follow-button'; // jshint ignore:line import misago from 'misago/index'; //jshint ignore:line export class SideNav extends React.Component { getMeta(meta) { if (meta) { // jshint ignore:start return <span className="badge">{this.props.profile[meta.attr]}</span>; // jshint ignore:end } else { return null; } } render() { // jshint ignore:start return <div className="list-group nav-side"> {this.props.pages.map((page) => { return <Link to={this.props.baseUrl + page.component + '/'} className="list-group-item" activeClassName="active" key={page.component}> <span className="material-icon"> {page.icon} </span> {page.name} {this.getMeta(page.meta)} </Link>; })} </div>; // jshint ignore:end } } export class CompactNav extends SideNav { showSpecialOptions() { return this.props.profile.acl.can_follow || this.props.profile.acl.can_moderate; } getFollowButton() { if (this.props.profile.acl.can_follow) { /* jshint ignore:start */ return <FollowButton className="btn btn-block" profile={this.props.profile} />; /* jshint ignore:end */ } else { return null; } } getModerationButton() { if (this.props.profile.acl.can_moderate) { /* jshint ignore:start */ return <button type="button" className="btn btn-default btn-block" onClick={this.props.toggleModeration}> <span className="material-icon"> tonality </span> {gettext("Moderation")} </button>; /* jshint ignore:end */ } else { return null; } } getSpecialOptions() { if (this.showSpecialOptions()) { /* jshint ignore:start */ return <li className="dropdown-buttons"> {this.getFollowButton()} {this.getModerationButton()} </li>; /* jshint ignore:end */ } else { return null; } } render() { // jshint ignore:start return <ul className="dropdown-menu" role="menu"> {this.getSpecialOptions()} {this.showSpecialOptions() ? <li className="divider" /> : null} {this.props.pages.map((page) => { return <Li path={this.props.baseUrl + page.component + '/'} key={page.component}> <Link to={this.props.baseUrl + page.component + '/'} onClick={this.props.hideNav}> <span className="material-icon"> {page.icon} </span> {page.name} {this.getMeta(page.meta)} </Link> </Li>; })} </ul>; // jshint ignore:end } }
src/Option.js
matroid/react-select
import React from 'react'; import classNames from 'classnames'; const Option = React.createClass({ propTypes: { children: React.PropTypes.node, className: React.PropTypes.string, // className (based on mouse position) instancePrefix: React.PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: React.PropTypes.bool, // the option is disabled isFocused: React.PropTypes.bool, // the option is focused isSelected: React.PropTypes.bool, // the option is selected onFocus: React.PropTypes.func, // method to handle mouseEnter on option element onSelect: React.PropTypes.func, // method to handle click on option element onUnfocus: React.PropTypes.func, // method to handle mouseLeave on option element option: React.PropTypes.object.isRequired, // object that is base for that option optionIndex: React.PropTypes.number, // index of the option, used to generate unique ids for aria }, blockEvent (event) { event.preventDefault(); event.stopPropagation(); if ((event.target.tagName !== 'A') || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }, handleMouseDown (event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter (event) { this.onFocus(event); }, handleMouseMove (event) { this.onFocus(event); }, 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; this.handleMouseDown(event); }, 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; }, onFocus (event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } }, render () { var { option, instancePrefix, optionIndex } = this.props; var className = classNames(this.props.className, option.className); return option.disabled ? ( <div className={className} onMouseDown={this.blockEvent} onClick={this.blockEvent}> {this.props.children} </div> ) : ( <div className={className} style={option.style} role="option" onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseMove={this.handleMouseMove} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd} id={instancePrefix + '-option-' + optionIndex} title={option.title}> {this.props.children} </div> ); } }); module.exports = Option;
client/routes.js
vilix13/SimpleMapApp
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App/App'; import About from './App/About'; import Map from './Map/Map'; import Auth from './Auth/Auth'; import requireAuth from './utils/requireAuth'; export default ( <Route path="/" component={App}> <IndexRoute component={requireAuth(Map)}/> <Route path="login" component={Auth} /> <Route path="about" component={About} /> </Route> );
src/index.js
superyorklin/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/social/person-add.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPersonAdd = (props) => ( <SvgIcon {...props}> <path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/> </SvgIcon> ); SocialPersonAdd = pure(SocialPersonAdd); SocialPersonAdd.displayName = 'SocialPersonAdd'; SocialPersonAdd.muiName = 'SvgIcon'; export default SocialPersonAdd;
packages/icons/src/md/hardware/LaptopMac.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLaptopMac(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M40 37h8c0 2.21-1.79 4-4 4H4c-2.21 0-4-1.79-4-4h8c-2.21 0-4-1.79-4-4V11c0-2.21 1.79-4 4-4h32c2.21 0 4 1.79 4 4l-.02 22c0 2.21-1.77 4-3.98 4zM8 11v22h32V11H8zm16 28c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z" /> </IconBase> ); } export default MdLaptopMac;
WasteApp/js/App.js
airien/workbits
import React, { Component } from 'react'; import { StyleSheet, AppState } from 'react-native'; import { Container, Content, Text, View } from 'native-base'; import Modal from 'react-native-modalbox'; import AppNavigator from './AppNavigator'; import ProgressBar from './components/loaders/ProgressBar'; import theme from './themes/base-theme'; var notifications = require('./data/notifications.json'); const timer = require('react-native-timer'); var PushNotification = require('react-native-push-notification'); const styles = StyleSheet.create({ container: { flex: 1, width: null, height: null, }, modal: { justifyContent: 'center', alignItems: 'center', }, modal1: { height: 300, }, }); class App extends Component { constructor(props) { super(props); this.state = { showDownloadingModal: false, showInstalling: false, downloadProgress: 0, }; } componentDidMount() { this.runNotification(); this.setState({ showDownloadingModal: false }); // AppState.addEventListener('change', this._handleAppStateChange); } componentWillUnmount() { // AppState.removeEventListener('change', this._handleAppStateChange); } render() { return <AppNavigator />; } runNotification() { PushNotification.localNotificationSchedule({ id: '1234525', // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID ticker: "Foodsaver", // (optional) subText: notifications[Math.floor(Math.random() * notifications.length) ], // (optional) default: none vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000 /* iOS and Android properties */ title: "Foodsaver", // (optional, for iOS this is only used in apple watch, the title will be the app name on other iOS devices) message: "Visste du at…", // (required) playSound: false, // (optional) default: true date: new Date(Date.now() + (172800000)), // in 2 days soundName: 'default' // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. }); }); } } export default App; PushNotification.configure({ // (optional) Called when Token is generated (iOS and Android) onRegister: function(token) { console.log( 'TOKEN:', token ); }, // (required) Called when a remote or local notification is opened or received onNotification: function(notification) { console.log( 'NOTIFICATION:', notification ); }, // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications) senderID: "YOUR GCM SENDER ID", // IOS ONLY (optional): default: all - Permissions to register. permissions: { alert: true, badge: true, sound: true }, // Should the initial notification be popped automatically // default: true popInitialNotification: true, /** * (optional) default: true * - Specified if permissions (ios) and token (android and ios) will requested or not, * - if not, you must call PushNotificationsHandler.requestPermissions() later */ requestPermissions: true, });
src/components/PageInnerContent.js
branch-bookkeeper/pina
import React from 'react'; import PropTypes from 'prop-types'; import Grid from '@material-ui/core/Grid'; const propTypes = { className: PropTypes.string, children: PropTypes.node, }; const defaultProps = { className: null, children: null, } const PageInnerContent = ({ className, children }) => ( <Grid container justify="center" className={className}> <Grid item xs={12} sm={9} md={8} lg={6} xl={4}> {children} </Grid> </Grid> ); PageInnerContent.propTypes = propTypes; PageInnerContent.defaultProps = defaultProps; export default PageInnerContent;
components/GoogleAnalytics/GoogleAnalytics.js
websiddu/reactable
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; import { googleAnalyticsId } from '../../config'; const trackingCode = { __html: `(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=` + `function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;` + `e=o.createElement(i);r=o.getElementsByTagName(i)[0];` + `e.src='https://www.google-analytics.com/analytics.js';` + `r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));` + `ga('create','${googleAnalyticsId}','auto');`, }; class GoogleAnalytics extends Component { render() { return <script dangerouslySetInnerHTML={trackingCode} />; } } export default GoogleAnalytics;
src/svg-icons/notification/airline-seat-legroom-normal.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomNormal = (props) => ( <SvgIcon {...props}> <path d="M5 12V3H3v9c0 2.76 2.24 5 5 5h6v-2H8c-1.66 0-3-1.34-3-3zm15.5 6H19v-7c0-1.1-.9-2-2-2h-5V3H6v8c0 1.65 1.35 3 3 3h7v7h4.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5z"/> </SvgIcon> ); NotificationAirlineSeatLegroomNormal = pure(NotificationAirlineSeatLegroomNormal); NotificationAirlineSeatLegroomNormal.displayName = 'NotificationAirlineSeatLegroomNormal'; NotificationAirlineSeatLegroomNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomNormal;
src/svg-icons/notification/sd-card.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSdCard = (props) => ( <SvgIcon {...props}> <path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 6h-2V4h2v4zm3 0h-2V4h2v4zm3 0h-2V4h2v4z"/> </SvgIcon> ); NotificationSdCard = pure(NotificationSdCard); NotificationSdCard.displayName = 'NotificationSdCard'; NotificationSdCard.muiName = 'SvgIcon'; export default NotificationSdCard;
examples/query-params/app.js
tylermcginnis/react-router
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' const User = ({ params: { userID }, location: { query } }) => { let age = query && query.showAge ? '33' : '' return ( <div className="User"> <h1>User id: {userID}</h1> {age} </div> ) } const App = ({ children }) => ( <div> <ul> <li><Link to="/user/bob" activeClassName="active">Bob</Link></li> <li><Link to={{ pathname: '/user/bob', query: { showAge: true } }} activeClassName="active">Bob With Query Params</Link></li> <li><Link to="/user/sally" activeClassName="active">Sally</Link></li> </ul> {children} </div> ) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <Route path="user/:userID" component={User} /> </Route> </Router> ), document.getElementById('example'))
client/src/modules/User/View.js
rikukissa/sql-exercises
import React, { Component } from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { round, sum, uniq, keys, values, groupBy, range, sortBy } from 'lodash'; import differenceInSeconds from 'date-fns/difference_in_seconds'; import format from 'date-fns/format'; import { getSessions } from '../../state'; const ExerciseLists = styled.div` `; const ExerciseList = styled.ul` border: 1px solid #ccc; list-style: none; margin-bottom: 1em; `; const ExerciseListHeader = styled.div` background: #f5e6d0; display: flex; justify-content: space-between; padding: 1em; `; const ExerciseListTitle = styled.div` display: flex; margin-left: 0.5em; align-items: center; `; const Success = styled.span` margin-right: 0.5em; `; const Tasks = styled.div` display: flex; float: right; `; const Task = styled.div` display: flex; font-weight: bold; margin: 0 3px; justify-content: center; align-items: center; width: 40px; height: 40px; border: 1px solid #ccc; background-color: #fff; `; const CorrectTask = styled(Task)` color: white; border: 1px solid #30b330; background-color: #2acc2a; position: relative; `; const IncorrectTask = styled(Task)` color: white; border: 1px solid #c70a2d; background-color: #ec0933; `; const Sessions = styled.div``; const Session = styled.div` border-top: 1px solid #ccc; padding: 0.5em; `; const SessionHeader = styled.div` font-weight: bold; margin-bottom: 0.5em; `; const SessionResults = styled.table` width: 100%; `; const Result = styled.td` font-weight: bold; text-align: right; `; function isCorrect(exerciseTries) { return exerciseTries.some((sessionTry) => sessionTry.correct); } function isCompleted(exerciseTries, maxTries) { return isCorrect(exerciseTries) || exerciseTries.length === maxTries; } function sortTriesByStart(tries) { return sortBy(tries, ({ startedAt }) => new Date(startedAt)); } function finishedExercises(session) { const triesPerExercise = values(groupBy(session.sessionTries, 'exercise')); return triesPerExercise.filter((tries) => isCorrect(tries)); } function fastestExerciseTime(session) { const triesPerExercise = groupBy(session.sessionTries, 'exercise'); return values(triesPerExercise).reduce( (memo, tries) => { const sortedTries = sortTriesByStart(tries); const start = sortedTries[0].startedAt; const end = sortedTries[sortedTries.length - 1].finishedAt; const time = differenceInSeconds(end, start); if (memo === null || time < memo) { return time; } return memo; }, null, ); } function slowestExerciseTime(session) { const triesPerExercise = groupBy(session.sessionTries, 'exercise'); return values(triesPerExercise).reduce( (memo, tries) => { const sortedTries = sortTriesByStart(tries); const start = sortedTries[0].startedAt; const end = sortedTries[sortedTries.length - 1].finishedAt; const time = differenceInSeconds(end, start); if (memo === null || time > memo) { return time; } return memo; }, null, ); } function averageExerciseTime(session) { const triesPerExercise = values(groupBy(session.sessionTries, 'exercise')); const times = triesPerExercise.map((tries) => { const sortedTries = sortTriesByStart(tries); const start = sortedTries[0].startedAt; const end = sortedTries[sortedTries.length - 1].finishedAt; return differenceInSeconds(end, start); }); return round(sum(times) / times.length, 2); } function getLatestSessionForExerciseList(exerciseList, sessions) { const sessionsForExerciseList = sessions.filter( (session) => session.exerciseList === exerciseList.id, ); if (sessionsForExerciseList.length === 0) { return null; } const sessionsSortedByTime = sortBy( sessionsForExerciseList, ({ startedAt }) => new Date(startedAt), ); return sessionsSortedByTime[sessionsSortedByTime.length - 1]; } function getTriesForNthExercise(exerciseN, session) { const triesPerExercise = groupBy(session.sessionTries, 'exercise'); const exerciseIds = uniq(values(triesPerExercise).map((tries) => tries[0].exercise)); if (exerciseIds[exerciseN] === undefined) { return []; } return triesPerExercise[exerciseIds[exerciseN]]; } class UserView extends Component { componentDidMount() { if (this.props.match.params.id) { this.props.getSessions(parseInt(this.props.match.params.id, 10)); return; } if (this.props.user) { this.props.getSessions(this.props.user.id); } } componentWillReceiveProps(nextProps) { const userLoaded = !this.props.user && nextProps.user; const idChanged = this.props.match.params.id !== nextProps.match.params.id; if (userLoaded || idChanged) { if (this.props.match.params.id) { this.props.getSessions(parseInt(nextProps.match.params.id, 10)); return; } this.props.getSessions(nextProps.user.id); } } getSessionsForExerciseList(exerciseList) { return this.props.sessions.filter((session) => session.exerciseList === exerciseList.id); } getUser = () => { if (!this.props.match.params.id) { return this.props.user; } const id = parseInt(this.props.match.params.id, 10); return this.props.users.find((user) => user.id === id); }; isExerciseCompleted(exerciseN, exerciseList) { const latestSession = getLatestSessionForExerciseList(exerciseList, this.props.sessions); if (!latestSession) { return false; } const tries = getTriesForNthExercise(exerciseN, latestSession); return isCompleted(tries, latestSession.maxTries); } isExerciseCorrect(exerciseN, exerciseList) { const latestSession = getLatestSessionForExerciseList(exerciseList, this.props.sessions); if (!latestSession) { return false; } const tries = getTriesForNthExercise(exerciseN, latestSession); return isCorrect(tries); } isExerciseListCompleted(list) { return this.props.sessions.some((session) => { const isRightList = session.exerciseList === list.id; if (!isRightList) { return false; } const triesPerExercise = groupBy(session.sessionTries, 'exercise'); if (keys(triesPerExercise).length < list.exerciseAmount) { return false; } const finished = values(triesPerExercise).filter((tries) => isCompleted(tries, session.maxTries)); return finished.length === list.exerciseAmount; }); } render() { const user = this.getUser(); const isMe = !user || !this.props.user || user.id === this.props.user.id; return ( <div> {isMe ? <h2>Omat suorituksesi</h2> : <h2>Käyttäjän {user.name} suoritukset</h2>} <ExerciseLists> {this.props.exerciseLists.map((exerciseList) => { const completed = this.isExerciseListCompleted(exerciseList); return ( <ExerciseList key={exerciseList.id}> <ExerciseListHeader key={exerciseList.id}> <ExerciseListTitle> {completed && <Success>✅</Success>} {exerciseList.description} </ExerciseListTitle> <Tasks> {range(exerciseList.exerciseAmount).map((i) => { const taskNum = i + 1; const taskCompleted = this.isExerciseCompleted(i, exerciseList); const taskCorrect = this.isExerciseCorrect(i, exerciseList); if (!taskCompleted) { return <Task key={i}>{taskNum}</Task>; } if (taskCorrect) { return <CorrectTask key={i}>{taskNum}</CorrectTask>; } return <IncorrectTask key={i}>{taskNum}</IncorrectTask>; })} </Tasks> </ExerciseListHeader> <Sessions> {this.getSessionsForExerciseList(exerciseList).map((session) => ( <Session key={session.id}> <SessionHeader> {format(session.startedAt, 'DD.MM.YYYY HH:mm')} </SessionHeader> {session.sessionTries.length === 0 && <span>Ei suoritettuja yrityskertoja</span>} {session.sessionTries.length > 0 && <SessionResults> <tbody> <tr> <td>Onnistuneiden tehtävien lukumäärä</td> <Result> {finishedExercises(session).length} {' '} / {' '} {exerciseList.exerciseAmount} </Result> </tr> <tr> <td>Nopein suoritusaika</td> <Result> {fastestExerciseTime(session)} sekuntia </Result> </tr> <tr> <td>Hitain suoritusaika</td> <Result> {slowestExerciseTime(session)} sekuntia </Result> </tr> <tr> <td>Keskimääräinen suoritusaika</td> <Result> {averageExerciseTime(session)} sekuntia </Result> </tr> </tbody> </SessionResults>} </Session> ))} </Sessions> </ExerciseList> ); })} </ExerciseLists> </div> ); } } function mapStateToProps(state) { return { user: state.user, users: state.users, sessions: state.sessions, exerciseLists: state.exerciseLists, }; } function mapDispatchToProps(dispatch) { return { getSessions: (userId) => dispatch(getSessions(userId)), }; } export default connect(mapStateToProps, mapDispatchToProps)(UserView);
ui/node_modules/react-bootstrap/src/ButtonGroup.js
bpatters/eservice
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const ButtonGroup = React.createClass({ mixins: [BootstrapMixin], propTypes: { vertical: React.PropTypes.bool, justified: React.PropTypes.bool }, getDefaultProps() { return { bsClass: 'button-group' }; }, render() { let classes = this.getBsClassSet(); classes['btn-group'] = !this.props.vertical; classes['btn-group-vertical'] = this.props.vertical; classes['btn-group-justified'] = this.props.justified; return ( <div {...this.props} className={classSet(this.props.className, classes)}> {this.props.children} </div> ); } }); export default ButtonGroup;
docs/src/examples/modules/Modal/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Content from './Content' import Types from './Types' import Variations from './Variations' import Usage from './Usage' const ModalExamples = () => ( <div> <Types /> <Content /> <Variations /> <Usage /> </div> ) export default ModalExamples
frontend/app/js/components/service/details/modal.js
serverboards/serverboards
import React from 'react' import Details from 'app/containers/service/details' import Modal from 'app/components/modal' import {goto} from 'app/utils/store' function ModalDetails(props){ let handleClose = undefined if (props.project) handleClose = () => goto(`/project/${props.project.shortname}/services`) return ( <Modal className="wide" onClose={handleClose}> <Details {...props}/> </Modal> ) } export default ModalDetails
eventkit_cloud/ui/static/ui/app/components/MapTools/InvalidDrawWarning.js
terranodo/eventkit-cloud
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withTheme } from '@material-ui/core/styles'; export class InvalidDrawWarning extends Component { render() { const { colors } = this.props.theme.eventkit; const style = { display: this.props.show ? 'initial' : 'none', position: 'absolute', top: '70px', right: '80px', width: '200px', border: '1px solid transparent', padding: '5px 5px 5px 10px', backgroundColor: colors.warning, borderColor: colors.warning, color: colors.white, zIndex: 2, opacity: 0.7, fontSize: '12px', }; return ( <div style={style} className="qa-InvalidDrawWardning-div"> <span>You drew an invalid bounding box, please redraw.</span> </div> ); } } InvalidDrawWarning.propTypes = { show: PropTypes.bool.isRequired, theme: PropTypes.object.isRequired, }; export default withTheme(InvalidDrawWarning);
examples/Toast.js
15lyfromsaturn/react-materialize
import React from 'react'; import Toast from '../src/Toast'; export default <Toast toast="here you go!"> Toast </Toast>;
src/svg-icons/device/battery-50.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
src/Help.js
networknt/react-schema-form
// @flow /** * Created by steve on 20/09/15. */ import React from 'react' import Typography from '@mui/material/Typography' type Props = { form: any } const Help = ({ form: { description, variant, align, color, noWrap, paragraph, otherProps } }: Props) => ( <Typography variant={variant} align={align} color={color} noWrap={noWrap} paragraph={paragraph} {...otherProps} > {description} </Typography> ) export default Help
src/components/Layout.js
hyyfrank/webpack_teach
import React from 'react'; import { Header, LeftMenu, Footer } from './comlayout'; import appstyle from './layout.less'; export default class LayoutComponent extends React.Component { render(){ return ( <div className={appstyle.main}> <div className={appstyle.left}> <LeftMenu /> </div> <div className={appstyle.right}> <Header /> <div className={appstyle.container}> {this.props.children} </div> <Footer /> </div> </div> ) } }
docs/src/app/components/pages/components/Stepper/HorizontalLinearStepper.js
hai-cea/material-ui
import React from 'react'; import { Step, Stepper, StepLabel, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; /** * Horizontal steppers are ideal when the contents of one step depend on an earlier step. * Avoid using long step names in horizontal steppers. * * Linear steppers require users to complete one step in order to move on to the next. */ class HorizontalLinearStepper extends React.Component { state = { finished: false, stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; this.setState({ stepIndex: stepIndex + 1, finished: stepIndex >= 2, }); }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'You\'re a long way from home sonny jim!'; } } render() { const {finished, stepIndex} = this.state; const contentStyle = {margin: '0 16px'}; return ( <div style={{width: '100%', maxWidth: 700, margin: 'auto'}}> <Stepper activeStep={stepIndex}> <Step> <StepLabel>Select campaign settings</StepLabel> </Step> <Step> <StepLabel>Create an ad group</StepLabel> </Step> <Step> <StepLabel>Create an ad</StepLabel> </Step> </Stepper> <div style={contentStyle}> {finished ? ( <p> <a href="#" onClick={(event) => { event.preventDefault(); this.setState({stepIndex: 0, finished: false}); }} > Click here </a> to reset the example. </p> ) : ( <div> <p>{this.getStepContent(stepIndex)}</p> <div style={{marginTop: 12}}> <FlatButton label="Back" disabled={stepIndex === 0} onClick={this.handlePrev} style={{marginRight: 12}} /> <RaisedButton label={stepIndex === 2 ? 'Finish' : 'Next'} primary={true} onClick={this.handleNext} /> </div> </div> )} </div> </div> ); } } export default HorizontalLinearStepper;
docs/app/Examples/collections/Form/States/FormExampleLoading.js
koenvg/Semantic-UI-React
import React from 'react' import { Button, Form, Input } from 'semantic-ui-react' const FormExampleLoading = () => ( <Form loading> <Form.Input label='Email' placeholder='joe@schmoe.com' /> <Button>Submit</Button> </Form> ) export default FormExampleLoading
packages/wix-style-react/src/CustomModalLayout/docs/examples/NoHeaderExample.js
wix/wix-style-react
/* eslint-disable */ import React from 'react'; import { Box, Checkbox } from 'wix-style-react'; class NoHeaderExample extends React.Component { render() { return ( <Box> <CustomModalLayout onCloseButtonClick={() => {}} primaryButtonText="Save" secondaryButtonText="Cancel" sideActions={(<Checkbox>Checkbox</Checkbox>)} footnote="footnote" > <Text> If you leave now, changes you have made here won't be saved. Are you sure you want to leave? </Text> </CustomModalLayout> </Box> ); } }
app/javascript/mastodon/components/column_back_button.js
pixiv/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class ColumnBackButton extends React.PureComponent { static contextTypes = { router: PropTypes.object, pawooPopHistory: PropTypes.func, }; handleClick = () => { this.context.pawooPopHistory(); } render () { return ( <button onClick={this.handleClick} className='column-back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); } }
webpack/move_to_pf/react-bootstrap-select/index.js
adamruzicka/katello
// This component should be replaced with a react version /* eslint-disable */ import React from 'react'; import ReactDOM from 'react-dom'; import { FormControl } from 'react-bootstrap'; import PropTypes from 'prop-types'; require('jquery'); require('bootstrap-select'); class BootstrapSelect extends React.Component { constructor(props) { super(props); this.state = { open: false }; } componentDidMount() { this.body = $('body'); this.select = $(ReactDOM.findDOMNode(this)); this.select.selectpicker(); this.container = this.select.parent(); this.button = this.container.find('button'); this.items = this.container.find('ul.dropdown-menu li a'); this.body.click(() => { this.setState({ open: false }); }); this.button.click(e => { e.stopPropagation(); this.setState({ open: !this.state.open }); }); this.items.click(() => { if (this.props.multiple) return; this.setState({ open: !this.state.open }); }); } componentDidUpdate() { this.select.selectpicker('refresh'); this.container.toggleClass('open', this.state.open); } componentWillUnmount() { this.body.off('click'); this.button.off('click'); this.items.off('click'); this.select.selectpicker('destroy'); } render() { // TODO: these classes are required because foreman assumes that all selects should use select2 and jquery multiselect // TODO: see also http://projects.theforeman.org/issues/21952 const { noneSelectedText, defaultValue, defaultValues, value, maxItemsCountForFullLabel, ...props} = this.props; const initialValue = defaultValues || defaultValue || value; return <FormControl {...props} data-none-selected-text={noneSelectedText} data-selected-text-format={`count>${maxItemsCountForFullLabel}`} data-count-selected-text={__('{0} items selected')} defaultValue={initialValue} componentClass="select" className="without_select2 without_jquery_multiselect" />; } } BootstrapSelect.propTypes = { noneSelectedText: PropTypes.string, defaultValue: PropTypes.string, defaultValues: PropTypes.arrayOf(PropTypes.string), maxItemsCountForFullLabel: PropTypes.number, }; BootstrapSelect.defaultProps = { noneSelectedText: __('Nothing selected'), maxItemsCountForFullLabel: 3, defaultValue: null, defaultValues: null, }; export default BootstrapSelect;
public/components/management/cluster/cluster-visualization.js
wazuh/wazuh-kibana-app
import React from 'react'; import KibanaVis from '../../../kibana-integrations/kibana-vis'; import { withErrorBoundary, withReduxProvider } from '../../../components/common/hocs'; import { compose } from 'redux'; export const KibanaVisWrapper = compose( withErrorBoundary, withReduxProvider )((props) => { return ( <div style={{ height: '100%' }}> <KibanaVis visID={props.visId} tab={props.tab}></KibanaVis> </div> ); });
packages/netlify-cms-core/src/components/MediaLibrary/MediaLibraryHeader.js
netlify/netlify-cms
import React from 'react'; import PropTypes from 'prop-types'; import styled from '@emotion/styled'; import { Icon, shadows, colors, buttons } from 'netlify-cms-ui-default'; const CloseButton = styled.button` ${buttons.button}; ${shadows.dropMiddle}; position: absolute; margin-right: -40px; left: -40px; top: -40px; width: 40px; height: 40px; border-radius: 50%; background-color: white; padding: 0; display: flex; justify-content: center; align-items: center; `; const LibraryTitle = styled.h1` line-height: 36px; font-size: 22px; text-align: left; margin-bottom: 25px; color: ${props => props.isPrivate && colors.textFieldBorder}; `; function MediaLibraryHeader({ onClose, title, isPrivate }) { return ( <div> <CloseButton onClick={onClose}> <Icon type="close" /> </CloseButton> <LibraryTitle isPrivate={isPrivate}>{title}</LibraryTitle> </div> ); } MediaLibraryHeader.propTypes = { onClose: PropTypes.func.isRequired, title: PropTypes.string.isRequired, isPrivate: PropTypes.bool, }; export default MediaLibraryHeader;
pootle/static/js/admin/components/ItemTable.js
iafan/zing
/* * 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 ItemTableRow from './ItemTableRow'; const ItemTable = React.createClass({ propTypes: { fields: React.PropTypes.array.isRequired, items: React.PropTypes.object.isRequired, resultsCaption: React.PropTypes.string.isRequired, selectedItem: React.PropTypes.object, onSelectItem: React.PropTypes.func.isRequired, }, render() { function createRow(item, index) { return ( <ItemTableRow fields={this.props.fields} key={item.id} item={item} index={index} selectedItem={this.props.selectedItem} onSelectItem={this.props.onSelectItem} /> ); } return ( <table> <caption>{this.props.resultsCaption}</caption> <tbody> {this.props.items.map(createRow.bind(this))} </tbody> </table> ); }, }); export default ItemTable;
docs/src/examples/addons/Radio/Types/RadioExampleRadio.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Radio } from 'semantic-ui-react' const RadioExampleRadio = () => <Radio label='Make my profile visible' /> export default RadioExampleRadio
boilerplate/App/Services/ExamplesRegistry.js
nonameolsson/ignite-ir-boilerplate
import React from 'react' import { Text, View } from 'react-native' import R from 'ramda' import { ApplicationStyles } from '../Themes' import DebugConfig from '../Config/DebugConfig' let globalComponentExamplesRegistry = [] let globalPluginExamplesRegistry = [] export const addComponentExample = (title, usage = () => {}) => { if (DebugConfig.includeExamples) globalComponentExamplesRegistry.push({title, usage}) } // eslint-disable-line export const addPluginExample = (title, usage = () => {}) => { if (DebugConfig.includeExamples) globalPluginExamplesRegistry.push({title, usage}) } // eslint-disable-line const renderComponentExample = (example) => { return ( <View key={example.title}> <View style={ApplicationStyles.darkLabelContainer}> <Text style={ApplicationStyles.darkLabel}>{example.title}</Text> </View> {example.usage.call()} </View> ) } const renderPluginExample = (example) => { return ( <View key={example.title}> <View style={ApplicationStyles.darkLabelContainer}> <Text style={ApplicationStyles.darkLabel}>{example.title}</Text> </View> {example.usage.call()} </View> ) } export const renderComponentExamples = () => R.map(renderComponentExample, globalComponentExamplesRegistry) export const renderPluginExamples = () => R.map(renderPluginExample, globalPluginExamplesRegistry) // Default for readability export default { renderComponentExamples, addComponentExample, renderPluginExamples, addPluginExample }
docs/src/PageFooter.js
15lyfromsaturn/react-materialize
import React from 'react'; import Footer from '../../src/Footer'; class PageFooter extends React.Component { render() { let links = ( <ul> <li> <a className="grey-text text-lighten-3" href='https://github.com/react-materialize/react-materialize'>GitHub</a> </li> </ul> ); let moreLinks = <a href='https://github.com/react-materialize/react-materialize/blob/master/LICENSE'>Code licensed under MIT</a>; return ( <Footer links={links} copyrights="© 2015 React Materialize, All rights reserved" moreLinks={moreLinks}> <h5 className="white-text">Join the Discussion</h5> <p className="grey-text text-lighten-4"> We have a Gitter chat room set up where you can talk directly with us. Come in and discuss new features, future goals, general problems or questions, or anything else you can think of. </p> <a href="https://gitter.im/react-materialize/react-materialize?utm_source=badge&amp;utm_medium=badge&amp;utm_campaign=pr-badge&amp;utm_content=badge"><img src="https://camo.githubusercontent.com/da2edb525cde1455a622c58c0effc3a90b9a181c/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667" alt="Join the chat at https://gitter.im/react-materialize/react-materialize" data-canonical-src="https://badges.gitter.im/Join%20Chat.svg"/> </a> </Footer> ); } } export default PageFooter;
docs/src/hero_example.js
mberneti/react-datepicker2
import React from 'react'; import momentJalaali from 'moment-jalaali'; import DatePicker from '../../src/index.dev.js'; import Switch from 'react-switch'; const buttonContainerStyle = { marginTop: 20 }; const labelStyle = { float: 'left' }; const switchStyle = { float: 'right' }; export default class ReactClass extends React.Component { constructor(props) { super(props); this.state = { value: momentJalaali(), checked: false }; this.handleChange = this.handleChange.bind(this); } handleChange(checked) { this.setState({ checked }); } render() { return ( <React.Fragment> <div> <DatePicker timePicker={false} isGregorian={this.state.checked} onChange={value => { this.setState({ value }); }} value={this.state.value} /> </div> <div style={buttonContainerStyle}> <label htmlFor="material-switch"> <span style={labelStyle}>isGregorian:{this.state.checked ? 'true' : 'false'}</span> <div style={switchStyle}> <Switch checked={this.state.checked} onChange={this.handleChange} onColor="#86ffa8" onHandleColor="#25e679" handleDiameter={23} uncheckedIcon={false} checkedIcon={false} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)" activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" height={15} width={38} className="react-switch" id="material-switch" /> </div> </label> </div> </React.Fragment> ); } }
src/main.js
fxghqc/walk
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { Router, useRouterHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import createStore from './store/createStore' import { Provider } from 'react-redux' const MOUNT_ELEMENT = document.getElementById('root') // Configure history for react-router const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the key "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const store = createStore(window.__INITIAL_STATE__, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) let render = (key = null) => { const routes = require('./routes/index').default(store) const App = ( <Provider store={store}> <div style={{ height: '100%' }}> <Router history={history} children={routes} key={key} /> </div> </Provider> ) ReactDOM.render(App, MOUNT_ELEMENT) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle if (__DEV__ && module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react') ReactDOM.render(<RedBox error={error} />, MOUNT_ELEMENT) } render = () => { try { renderApp(Math.random()) } catch (error) { renderError(error) } } module.hot.accept(['./routes/index'], () => render()) } // Use Redux DevTools chrome extension if (__DEBUG__) { if (window.devToolsExtension) window.devToolsExtension.open() } render()
src/svg-icons/image/edit.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageEdit = (props) => ( <SvgIcon {...props}> <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/> </SvgIcon> ); ImageEdit = pure(ImageEdit); ImageEdit.displayName = 'ImageEdit'; ImageEdit.muiName = 'SvgIcon'; export default ImageEdit;
src/client/components/PageSpinner.js
eliasmeire/hz-pictionary
import React from 'react'; import Spinning from 'grommet/components/icons/Spinning'; const PageSpinner = ({ size } = { size: 'huge' }) => ( <div className="app-wrapper"> <div className="main-content"> <Spinning size={size} /> </div> </div> ); export default PageSpinner;
mobile/App/Containers/ListviewExample.js
JasonQSong/SoulDistance
// @flow import React from 'react' import { View, Text, ListView } from 'react-native' import { connect } from 'react-redux' // For empty lists import AlertMessage from '../Components/AlertMessage' // Styles import styles from './Styles/ListviewExampleStyle' class ListviewExample extends React.Component { state: { dataSource: Object } constructor (props) { super(props) /* *********************************************************** * STEP 1 * This is an array of objects with the properties you desire * Usually this should come from Redux mapStateToProps *************************************************************/ const dataObjects = [ {title: 'First Title', description: 'First Description'}, {title: 'Second Title', description: 'Second Description'}, {title: 'Third Title', description: 'Third Description'}, {title: 'Fourth Title', description: 'Fourth Description'}, {title: 'Fifth Title', description: 'Fifth Description'}, {title: 'Sixth Title', description: 'Sixth Description'}, {title: 'Seventh Title', description: 'Seventh Description'}, {title: 'Eighth Title', description: 'Eighth Description'}, {title: 'Ninth Title', description: 'Ninth Description'}, {title: 'Tenth Title', description: 'Tenth Description'}, {title: 'Eleventh Title', description: 'Eleventh Description'}, {title: '12th Title', description: '12th Description'}, {title: '13th Title', description: '13th Description'}, {title: '14th Title', description: '14th Description'}, {title: '15th Title', description: '15th Description'}, {title: '16th Title', description: '16th Description'}, {title: '17th Title', description: '17th Description'}, {title: '18th Title', description: '18th Description'}, {title: '19th Title', description: '19th Description'}, {title: '20th Title', description: '20th Description'}, {title: 'BLACKJACK!', description: 'BLACKJACK! Description'} ] /* *********************************************************** * STEP 2 * Teach datasource how to detect if rows are different * Make this function fast! Perhaps something like: * (r1, r2) => r1.id !== r2.id} *************************************************************/ const rowHasChanged = (r1, r2) => r1 !== r2 // DataSource configured const ds = new ListView.DataSource({rowHasChanged}) // Datasource is always in state this.state = { dataSource: ds.cloneWithRows(dataObjects) } } /* *********************************************************** * STEP 3 * `renderRow` function -How each cell/row should be rendered * It's our best practice to place a single component here: * * e.g. return <MyCustomCell title={rowData.title} description={rowData.description} /> *************************************************************/ renderRow (rowData) { return ( <View style={styles.row}> <Text style={styles.boldLabel}>{rowData.title}</Text> <Text style={styles.label}>{rowData.description}</Text> </View> ) } /* *********************************************************** * STEP 4 * If your datasource is driven by Redux, you'll need to * reset it when new data arrives. * DO NOT! place `cloneWithRows` inside of render, since render * is called very often, and should remain fast! Just replace * state's datasource on newProps. * * e.g. componentWillReceiveProps (newProps) { if (newProps.someData) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(newProps.someData) }) } } *************************************************************/ // Used for friendly AlertMessage // returns true if the dataSource is empty noRowData () { return this.state.dataSource.getRowCount() === 0 } render () { return ( <View style={styles.container}> <AlertMessage title='Nothing to See Here, Move Along' show={this.noRowData()} /> <ListView contentContainerStyle={styles.listContent} dataSource={this.state.dataSource} renderRow={this.renderRow} pageSize={15} /> </View> ) } } const mapStateToProps = (state) => { return { // ...redux state to props here } } export default connect(mapStateToProps)(ListviewExample)
src/svg-icons/device/screen-lock-rotation.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenLockRotation = (props) => ( <SvgIcon {...props}> <path d="M23.25 12.77l-2.57-2.57-1.41 1.41 2.22 2.22-5.66 5.66L4.51 8.17l5.66-5.66 2.1 2.1 1.41-1.41L11.23.75c-.59-.59-1.54-.59-2.12 0L2.75 7.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12zM8.47 20.48C5.2 18.94 2.86 15.76 2.5 12H1c.51 6.16 5.66 11 11.95 11l.66-.03-3.81-3.82-1.33 1.33zM16 9h5c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1v-.5C21 1.12 19.88 0 18.5 0S16 1.12 16 2.5V3c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1zm.8-6.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V3h-3.4v-.5z"/> </SvgIcon> ); DeviceScreenLockRotation = pure(DeviceScreenLockRotation); DeviceScreenLockRotation.displayName = 'DeviceScreenLockRotation'; DeviceScreenLockRotation.muiName = 'SvgIcon'; export default DeviceScreenLockRotation;
src/views/components/kb/LearnerQuestionsOverview.js
Domiii/project-empire
import { LearnerQuestionTypes } from 'src/core/scaffolding/LearnerKBModel'; import size from 'lodash/size'; import map from 'lodash/map'; import { hrefLearnerStatusList } from 'src/views/href'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { dataBind } from 'dbdi/react'; import Moment from 'react-moment'; import { Alert, Button, Panel } from 'react-bootstrap'; import UserBadge from 'src/views/components/users/UserBadge'; import LoadIndicator from 'src/views/components/util/LoadIndicator'; import FAIcon from 'src/views/components/util/FAIcon'; import LearnerQuestionList from './LearnerQuestionList'; @dataBind({ addQuestionClick(evt, { }, { push_learnerQuestion }) { const q = { title: '', description: '', questionType: LearnerQuestionTypes.YesNo }; return push_learnerQuestion(q); } }) export default class LearnerQuestionsOverview extends Component { constructor(...args) { super(...args); this.state = { editId: null }; this.dataBindMethods( '_onUpdate', 'clickAdd' ); } componentWillMount() { this._onUpdate(this.props); } /** * This works even when we use DB data since DB data is sent via context updates. * see: https://github.com/facebook/react/pull/5787 */ componentWillReceiveProps(nextProps) { this._onUpdate(nextProps); } _onUpdate(nextProps, { }, { }, { learnerQuestionList } ) { // check if question has been deleted const { editId } = this.state; if (editId && ( !learnerQuestionList || !learnerQuestionList[editId] )) { this.setState({ editId: null }); } } clickAdd = (evt, { }, { addQuestionClick }, { }) => { const newRef = addQuestionClick(evt); this.setState({ editId: newRef.key }); } setEditing = (editId) => { this.setState({ editId }); } render( { }, { }, { learnerQuestionList } ) { return (<div> <h3> Learner Questions ({size(learnerQuestionList)}) </h3> <LearnerQuestionList editId={this.state.editId} setEditing={this.setEditing} /> <center className="full-width"> {!this.state.editId && <Button bsStyle="success" onClick={this.clickAdd}> <FAIcon name="plus" /> Add Question! </Button> } </center> </div>); } }
examples/async/index.js
csaden/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
tests/GeoDistanceSlider/GeoDistanceSlider.js
appbaseio/reactive-maps
import React from 'react'; import { ReactiveBase, GeoDistanceSlider, ReactiveMap } from '../../app/app.js'; import {config} from './config'; import { mount } from 'enzyme'; var GoogleMapsLoader = require('google-maps'); GoogleMapsLoader.KEY = 'AIzaSyC-v0oz7Pay_ltypZbKasABXGiY9NlpCIY'; GoogleMapsLoader.VERSION = 3.14; GoogleMapsLoader.LIBRARIES = ['geometry', 'places']; var google; function testComponent(cb) { const onData = function(res, err) { cb(res, err); } const component = mount( <ReactiveBase app={config.ReactiveBase.app} username={config.ReactiveBase.username} password={config.ReactiveBase.password} type={config.ReactiveBase.type} > <div className="row"> <div className="col s6 col-xs-6"> <GeoDistanceSlider componentId="CitySensor" appbaseField={config.mapping.location} title="GeoDistanceSlider" defaultSelected={config.GeoDistanceSlider.defaultSelected} unit={config.GeoDistanceSlider.unit} range={{ start: 1, end: 60 }} /> </div> <div className="col s6 col-xs-6"> <ReactiveMap componentId="SearchResult" appbaseField={config.mapping.location} onData={onData} size={config.ReactiveMap.size} react={{ 'and': ["CitySensor"] }} /> </div> </div> </ReactiveBase> ); } export var GeoDistanceSliderTest = function() { return new Promise((resolve, reject) => { GoogleMapsLoader.load(function(googleLoad) { google = googleLoad; window.google = googleLoad; start(); }); function start() { testComponent(function(res,err) { if (err) { reject(err); } else if (res) { resolve(res); } }); } }); }
src/ModalHeader.js
brynjagr/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalHeader extends React.Component { render() { return ( <div {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> { this.props.closeButton && <button className="close" onClick={this.props.onHide}> <span aria-hidden="true"> &times; </span> </button> } { this.props.children } </div> ); } } // used in liue of parent contexts right now to auto wire the close button ModalHeader.__isModalHeader = true; ModalHeader.propTypes = { /** * The 'aria-label' attribute is used to define a string that labels the current element. * It is used for Assistive Technology when the label text is not visible on screen. */ 'aria-label': React.PropTypes.string, /** * A css class applied to the Component */ modalClassName: React.PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: React.PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside a Modal component, the onHide will automatically * be propagated up to the parent Modal `onHide`. */ onHide: React.PropTypes.func }; ModalHeader.defaultProps = { 'aria-label': 'Close', modalClassName: 'modal-header', closeButton: false }; export default ModalHeader;
src/components/UnitView/instructions/InputText.js
fkn/ndo
import _ from 'lodash'; import React from 'react'; import Base from './Base'; /** * <input name="" type="text|color"> */ export default class InputText extends Base { constructor(root) { super(root, 'input', { name: { $exists: true }, type: 'text' }); } processNode(node, children, index) { const name = _.get(node, 'attribs.name'); const renderAttrs = Base.inputRenderAttrs(node, children, index); const valueAttrs = { value: this.root.state.answers[name] || _.get(node, 'attribs.value', ''), onChange: event => this.root.setAnswer(name, event.target.value), }; return <input {...renderAttrs} {...valueAttrs} />; } }
App/db/entities/content/FocusedItems.js
nthbr/mamasound.fr
/* * Copyright (c) 2017. Caipi Labs. All rights reserved. * * This File is part of Caipi. 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/>. * This project is dual licensed under AGPL and Commercial Licence. * * @author : Nathanael Braun * @contact : caipilabs@gmail.com */ /** * @author Nathanael BRAUN * * Date: 24/11/2015 * Time: 19:18 */ import React from 'react'; import {types, validate} from 'App/db/field'; export default { label : "Contenu mis en avant", apiRroute : "Focused", adminRoute : "Contenu/Mis en avant", processResult : { "get" : function ( record, cuser ) { if ( !record._public ) if ( !cuser || !cuser.isPublisher ) { //console.log('hidden', record); return null; } return record; } }, //views : { // "preview" : require("App/ui/components/Focus_Preview"), // require here so webpack should not require all the views //// "preview" : require("core/defaultRenderer/Preview") // require here so webpack should not require all the views //}, autoMount : ["targetEtty"], schema : { label : [validate.mandatory, validate.noHtml], previewUrl : [validate.mandatory], resume : [validate.noJs], text : [validate.noJs], item_link : [validate.noJs, validate.isUrl], // author : [validate.mandatory] }, fields : { "_id" : types.indexes, //"pubFlag" : fields.publicationFlag, "_public" : types.boolean("Publier :", false), //"publishTs" : "<timestamp>",// ? "label" : types.labels(), "previewImage" : types.media({allowedTypes:"Image"}, "Background :"), "resume" : types.descriptions('Resumé'), // TODO refactor as "summary" "targetEtty" : types.picker(true, { allowTypeSelection : ["Concert","Theatre","Expo","Article","Collection","Video","Page"], storeTypedItem: true, }, "Contenu cible :"), // //"author" : fields.picker(true, { // allowTypeSelection : ["MusicHunter", "Proposer", "Talent"], // storeTypedItem: true, //}, "Sélectionner l'auteur"), //"placeId" : fields.picker("Place", {}), // //"tagId" : fields.picker("Tag"), //"items" : fields.collection(null, {}, "Cible :"), //"item_link" : fields.labels("Cibler via un lien") // } };
examples/01 Dustbin/Stress Test/Container.js
globexdesigns/react-dnd
import React, { Component } from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend, { NativeTypes } from 'react-dnd-html5-backend'; import Dustbin from './Dustbin'; import Box from './Box'; import ItemTypes from './ItemTypes'; import shuffle from 'lodash/shuffle'; import update from 'react/lib/update'; @DragDropContext(HTML5Backend) export default class Container extends Component { constructor(props) { super(props); this.state = { dustbins: [ { accepts: [ItemTypes.GLASS], lastDroppedItem: null }, { accepts: [ItemTypes.FOOD], lastDroppedItem: null }, { accepts: [ItemTypes.PAPER, ItemTypes.GLASS, NativeTypes.URL], lastDroppedItem: null }, { accepts: [ItemTypes.PAPER, NativeTypes.FILE], lastDroppedItem: null } ], boxes: [ { name: 'Bottle', type: ItemTypes.GLASS }, { name: 'Banana', type: ItemTypes.FOOD }, { name: 'Magazine', type: ItemTypes.PAPER } ], droppedBoxNames: [] }; } componentDidMount() { this.interval = setInterval(() => this.tickTock(), 1000); } tickTock() { this.setState({ boxes: shuffle(this.state.boxes), dustbins: shuffle(this.state.dustbins) }); } componentWillUnmount() { clearInterval(this.interval); } isDropped(boxName) { return this.state.droppedBoxNames.indexOf(boxName) > -1; } render() { const { boxes, dustbins } = this.state; return ( <div> <div style={{ overflow: 'hidden', clear: 'both' }}> {dustbins.map(({ accepts, lastDroppedItem }, index) => <Dustbin accepts={accepts} lastDroppedItem={lastDroppedItem} onDrop={(item) => this.handleDrop(index, item)} key={index} /> )} </div> <div style={{ overflow: 'hidden', clear: 'both' }}> {boxes.map(({ name, type }, index) => <Box name={name} type={type} isDropped={this.isDropped(name)} key={index} /> )} </div> </div> ); } handleDrop(index, item) { const { name } = item; this.setState(update(this.state, { dustbins: { [index]: { lastDroppedItem: { $set: item } } }, droppedBoxNames: name ? { $push: [name] } : {} })); } }
app/javascript/mastodon/components/avatar_composite.js
pso2club/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class AvatarComposite extends React.PureComponent { static propTypes = { accounts: ImmutablePropTypes.list.isRequired, animate: PropTypes.bool, size: PropTypes.number.isRequired, }; static defaultProps = { animate: autoPlayGif, }; renderItem (account, size, index) { const { animate } = this.props; let width = 50; let height = 100; let top = 'auto'; let left = 'auto'; let bottom = 'auto'; let right = 'auto'; if (size === 1) { width = 100; } if (size === 4 || (size === 3 && index > 0)) { height = 50; } if (size === 2) { if (index === 0) { right = '2px'; } else { left = '2px'; } } else if (size === 3) { if (index === 0) { right = '2px'; } else if (index > 0) { left = '2px'; } if (index === 1) { bottom = '2px'; } else if (index > 1) { top = '2px'; } } else if (size === 4) { if (index === 0 || index === 2) { right = '2px'; } if (index === 1 || index === 3) { left = '2px'; } if (index < 2) { bottom = '2px'; } else { top = '2px'; } } const style = { left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%`, backgroundSize: 'cover', backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`, }; return ( <div key={account.get('id')} style={style} /> ); } render() { const { accounts, size } = this.props; return ( <div className='account__avatar-composite' style={{ width: `${size}px`, height: `${size}px` }}> {accounts.take(4).map((account, i) => this.renderItem(account, accounts.size, i))} </div> ); } }
app/components/presentation/HostelForm.js
PHPiotr/phpiotr4
import React from 'react'; import Button from 'material-ui/Button'; import {FormControl} from 'material-ui/Form'; import {EDIT_HOSTEL, NEW_HOSTEL} from '../../constants'; import Booking from '../containers/Booking'; import Input, {InputLabel} from 'material-ui/Input'; import {withStyles} from 'material-ui/styles'; import {formStyles as styles} from '../../utils/styles'; const HostelForm = (props) => { const {hostel} = props; return ( <form className={props.classes.root} onSubmit={props.handleSubmit}> <FormControl component="fieldset"> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Code: ${(hostel.errors.booking_number && !!hostel.errors.booking_number.message) ? hostel.errors.booking_number.message : ''}`}</InputLabel> <Input id={'booking-number'} type={'text'} name={'booking_number'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.booking_number || ''} error={hostel.errors.booking_number && !!hostel.errors.booking_number.message} /> </FormControl> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Hostel name: ${(hostel.errors.hostel_name && !!hostel.errors.hostel_name.message) ? hostel.errors.hostel_name.message : ''}`}</InputLabel> <Input id={'hostel-name'} type={'text'} name={'hostel_name'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.hostel_name || ''} error={hostel.errors.hostel_name && !!hostel.errors.hostel_name.message} /> </FormControl> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Hostel address: ${(hostel.errors.hostel_address && !!hostel.errors.hostel_address.message) ? hostel.errors.hostel_address.message : ''}`}</InputLabel> <Input id={'hostel-address'} type={'text'} name={'hostel_address'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.hostel_address || ''} error={hostel.errors.hostel_address && !!hostel.errors.hostel_address.message} /> </FormControl> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Check-in date: ${(hostel.errors.checkin_date && !!hostel.errors.checkin_date.message) ? hostel.errors.checkin_date.message : ''}`}</InputLabel> <Input inputProps={{max: hostel.current.checkout_date || ''}} id={'checkin-date'} type={'date'} name={'checkin_date'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.checkin_date || ''} error={hostel.errors.checkin_date && !!hostel.errors.checkin_date.message} /> </FormControl> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Check-out date: ${(hostel.errors.checkout_date && !!hostel.errors.checkout_date.message) ? hostel.errors.checkout_date.message : ''}`}</InputLabel> <Input inputProps={{min: hostel.current.checkin_date || ''}} id={'checkout-date'} type={'date'} name={'checkout_date'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.checkout_date || ''} error={hostel.errors.checkout_date && !!hostel.errors.checkout_date.message} /> </FormControl> <FormControl className={props.classes.formControl}> <InputLabel htmlFor="password">{`Price: ${(hostel.errors.price && !!hostel.errors.price.message) ? hostel.errors.price.message : ''}`}</InputLabel> <Input id={'price'} type={'text'} name={'price'} onChange={props.handleChange} onFocus={props.handleFocus} value={hostel.current.price || '0.00'} error={hostel.errors.price && !!hostel.errors.price.message} /> </FormControl> <FormControl className={props.classes.formControl}> <Button variant="raised" color="primary" type="submit">Save</Button> </FormControl> </FormControl> </form> ); }; HostelForm.bookingsLabel = 'hostels'; HostelForm.bookingLabel = 'hostel'; HostelForm.newLabel = NEW_HOSTEL; HostelForm.editLabel = EDIT_HOSTEL; export default withStyles(styles)(Booking(HostelForm));
public/js/pages/WorkshopPage.js
JasonShin/HELP-yo
/** * Created by Shin on 1/10/2016. */ import React from 'react'; import WorkshopsStore from '../stores/WorkshopsStore'; import animationConstants from '../constants/animationConstants'; const ReactCSSTransitionGroup = require('react-addons-css-transition-group'); import Single from '../components/Single'; export default class Workshop extends React.Component { constructor() { super(); this.state = { currentWorkshop: null }; } componentWillMount() { const {workshopId} = this.props.location.query; WorkshopsStore.findWorkshopById(workshopId); this.setState({ workshopId }); } render() { const {workshopId} = this.state; return ( <div> <Single workshopStore={WorkshopsStore} workshopId={workshopId} /> </div> ) } }
js/jqwidgets/demos/react/app/rangeselector/righttoleftlayout/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxRangeSelector from '../../../jqwidgets-react/react_jqxrangeselector.js'; class App extends React.Component { componentDidMount() { this.refs.myRangeSelector.setRange(30, 60); } render() { return ( <JqxRangeSelector ref='myRangeSelector' width={750} height={100} min={0} max={100} minorTicksInterval={1} majorTicksInterval={10} range={{ from: 40, to: 60 }} rtl={true} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
client/src/component/common/item-form.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import * as UU5 from 'uu5g03'; import {browserHistory} from 'react-router'; import Utils from '../../utils'; import ItemWizard from './item-wizard.js'; import PropertyNewModal from './property-new-modal.js'; import PropertyEditModal from './property-edit-modal.js'; import PropertyRemoveModal from './property-remove-modal.js'; import StageNewModal from './stage-new-modal.js'; import StageEditModal from './stage-edit-modal.js'; import StageRemoveModal from './stage-remove-modal.js'; import TypeNewModal from './type-new-modal.js'; import TypeEditModal from './type-edit-modal.js'; import TypeRemoveModal from './type-remove-modal.js'; import AssemblyChildNewModal from './assembly-child-new-modal.js'; import AssemblyChildEditModal from './assembly-child-edit-modal.js'; import AssemblyChildRemoveModal from './assembly-child-remove-modal.js'; import Calls from '../../calls.js'; import './item-form.css'; let ComponentItemForm = React.createClass( { mixins: [ UU5.Common.BaseMixin, UU5.Common.ElementaryMixin, UU5.Layout.RowMixin, UU5.Common.CcrReaderMixin, UU5.Common.CallsMixin ], statics: { tagName: 'Ucl.Itkpd.Configurator.Components.ItemForm', classNames: { main: 'ucl-itkpd-configurator-component-item-form', basicForm: 'ucl-itkpd-configurator-component-item-form', btnForm:'ucl-itkpd-configurator-component-item-form-btn-form', submitBtn:'btn-itk-submit', cancelBtn:'btn-itk-cancel', defaultBtn:'btn-itk-default' }, calls: { create: 'createComponentType', update: 'updateComponentType', listSubprojects: 'listSubprojects' } }, //@@viewOn:propTypes propTypes: { project: React.PropTypes.string, action: React.PropTypes.string, componentId: React.PropTypes.string, code: React.PropTypes.string, componentName: React.PropTypes.string, category: React.PropTypes.string, subprojects: React.PropTypes.array, snRequired: React.PropTypes.bool, snComponentCode: React.PropTypes.string, types: React.PropTypes.object, properties: React.PropTypes.object, stages: React.PropTypes.object, children: React.PropTypes.object, subprojectList: React.PropTypes.array }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps() { return { project: Utils.getParamValue("project"), action: "new", componentId: "", code: "", componentName: "", category: "", subprojects: [], snRequired: false, types: {}, properties: {}, stages: {}, children: {}, snComponentCode: "" }; }, //@@viewOff:getDefaultProps getInitialState(){ return { wizardStep: "basicProperties", componentId: this.props.componentId, category: this.props.category, subprojects: this.props.subprojects } }, setWizardSet(step) { this.setState({wizardStep: step}); }, _handleSubmitForm(next) { if (this.state.wizardStep === "basicProperties") { if (this.getCcrComponentByKey('Ucl.Itkpd.Configurator.ComponentItemFormWizardBasicProperties').isValid()) { let formData; formData = this.getCcrComponentByKey('Ucl.Itkpd.Configurator.ComponentItemFormWizardBasicProperties').getValues(); let category = formData.category; let subprojects = formData.subprojects; if (formData) { this.getCall((this.props.action === "new" ? "create" : "update")) ( { data:{ id: this.props.componentId, code: formData.code.toUpperCase(), name: formData.name, project: Utils.getProjectCodeByName(formData.project), subprojects: formData.subprojects, category: formData.category, snRequired: (formData.snRequired === true), snComponentCode: formData.snComponentCode }, done:(dtoOut) => { this.getCcrComponentByKey('Ucl.Itkpd.Configurator.ComponentItemFormWizardBasicProperties').reset(); // Reset of basicForm input forms next ? (this.props.action === "new") ? this.setState({componentId: dtoOut["id"], subprojects: subprojects, wizardStep: "types", category: category}) : this.setState({wizardStep: "types", category: category, subprojects: subprojects}) : browserHistory.goBack(); }, fail:(dtoOut) =>{ console.error(dtoOut); } } ); } } } else if (this.state.wizardStep === "types") { this.setState({wizardStep: "properties"}); } else if (this.state.wizardStep === "properties") { this.setState({wizardStep: "stages"}); } else if (this.state.wizardStep === "stages") { (this.state.category === "assembly" || this.state.category === "wafer") ? this.setState({wizardStep: "assemblyParts"}) : browserHistory.goBack(); } else if (this.state.wizardStep === "assemblyParts") { browserHistory.goBack(); } }, _getFormButtons() { let saveLabel, saveAndNextLabel, cancelLabel, buttons; if (this.state.wizardStep === "basicProperties") { (this.props.action === "new") ? saveLabel = "Add & Close" : saveLabel = "Update & Close"; (this.props.action === "new") ? saveAndNextLabel = "Add & Next" : saveAndNextLabel = "Update & Next"; cancelLabel = "Cancel"; buttons = ( <UU5.Bricks.Div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={saveAndNextLabel} onClick={() => this._handleSubmitForm(true)} className={this.getClassName().submitBtn} /> <UU5.Bricks.Button content={saveLabel} onClick={() => this._handleSubmitForm(false)} className={this.getClassName().defaultBtn} /> <UU5.Bricks.Button content={cancelLabel} onClick={browserHistory.goBack} className={this.getClassName().cancelBtn} /> </UU5.Bricks.Div> ); } else if (this.state.wizardStep === "types") { buttons = ( <div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={"Next"} onClick={this._handleSubmitForm} className={this.getClassName().submitBtn} /> <UU5.Bricks.Button content={"Close"} onClick={browserHistory.goBack} className={this.getClassName().cancelBtn} /> </div> ); } else if (this.state.wizardStep === "properties") { buttons = ( <div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={"Next"} onClick={this._handleSubmitForm} className={this.getClassName().submitBtn} /> <UU5.Bricks.Button content={"Close"} onClick={browserHistory.goBack} className={this.getClassName().cancelBtn} /> </div> ); } else if (this.state.wizardStep === "stages") { if (this.state.category === "assembly") { buttons = ( <div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={"Next"} onClick={this._handleSubmitForm} className={this.getClassName().submitBtn} /> <UU5.Bricks.Button content={"Close"} onClick={browserHistory.goBack} className={this.getClassName().cancelBtn} /> </div> ); } else { buttons = ( <div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={"Close"} onClick={this._handleSubmitForm} className={this.getClassName().submitBtn} /> </div> ); } } else if (this.state.wizardStep === "assemblyParts") { buttons = ( <div className={this.getClassName().btnForm}> <UU5.Bricks.Button content={"Close"} onClick={this._handleSubmitForm} className={this.getClassName().submitBtn} /> </div> ); } return ( <UU5.Layout.Column> {buttons} </UU5.Layout.Column> ) }, _getWizardBar() { let content; let childrenStep = ( <UU5.Bricks.Link className={(this.state.wizardStep === "assemblyParts" ? "current" : "")}><UU5.Bricks.Badge content="4"></UU5.Bricks.Badge> Assembly Parts</UU5.Bricks.Link> ); content = ( <div className="wizard"> <UU5.Bricks.Link className={(this.state.wizardStep === "basicProperties" ? "current" : "")}><UU5.Bricks.Badge content="1"></UU5.Bricks.Badge> Basic Properties</UU5.Bricks.Link> <UU5.Bricks.Link className={(this.state.wizardStep === "types" ? "current" : "")}><UU5.Bricks.Badge content="2"></UU5.Bricks.Badge> Types</UU5.Bricks.Link> <UU5.Bricks.Link className={(this.state.wizardStep === "properties" ? "current" : "")}><UU5.Bricks.Badge content="3"></UU5.Bricks.Badge> Properties</UU5.Bricks.Link> <UU5.Bricks.Link className={(this.state.wizardStep === "stages" ? "current" : "")}><UU5.Bricks.Badge content="4"></UU5.Bricks.Badge> Stages</UU5.Bricks.Link> {(this.state.category === "assembly" || this.state.category === "wafer") && (childrenStep)} </div> ); return content; }, render() { return ( <UU5.Layout.Row {...this.getMainPropsToPass()} > <UU5.Layout.Column> {this._getWizardBar()} <div className={this.getClassName().basicForm}> <ItemWizard ccrKey="Ucl.Itkpd.Configurator.ComponentItemFormWizard" calls={Calls} wizardStep={this.state.wizardStep} action={this.props.action} componentId={this.state.componentId} code={this.props.code} project={this.props.project} componentName={this.props.componentName} category={this.props.category} subprojects={this.props.subprojects} snComponentCode={this.props.snComponentCode} snRequired={this.props.snRequired} properties={this.props.properties} types={this.props.types} stages={this.props.stages} subprojectList={this.props.subprojectList} children={this.props.children} /> </div> <TypeNewModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.TypeNewModal" subprojects={this.state.subprojects} subprojectList={this.props.subprojectList} /> <TypeEditModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.TypeEditModal" subprojects={this.state.subprojects} subprojectList={this.props.subprojectList} /> <TypeRemoveModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.TypeRemoveModal" /> <PropertyNewModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.PropertyNewModal" /> <PropertyEditModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.PropertyEditModal" /> <PropertyRemoveModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.PropertyRemoveModal" /> <StageNewModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.StageNewModal" /> <StageEditModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.StageEditModal" /> <StageRemoveModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.StageRemoveModal" /> <AssemblyChildNewModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.AssemblyChildNewModal" calls={Calls} /> <AssemblyChildEditModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.AssemblyChildEditModal" /> <AssemblyChildRemoveModal ccrKey="Ucl.Itkpd.Configurator.ComponentItem.AssemblyChildRemoveModal" /> </UU5.Layout.Column> {this._getFormButtons()} </UU5.Layout.Row> ); } //@@viewOn:render }); export default ComponentItemForm;
src/components/MySunburst.js
nordicbikes/nordicbikes.github.io
import React from 'react'; import SunBurst from 'grommet/components/SunBurst'; import Box from 'grommet/components/Box'; import Legend from 'grommet/components/Legend'; import Value from 'grommet/components/Value'; class MySunburst extends React.Component { render() { return ( <Box direction="row" align="center" pad={{"between": "medium"}}> <SunBurst data={[ { "label": "root-1", "value": 50, "colorIndex": "neutral-1", "children": [ { "label": "sub-1", "value": 20, "colorIndex": "neutral-1", "total": 10, "children": [ {"label": "leaf-1", "value": 5, "colorIndex": "neutral-1"}, {"label": "leaf-2", "value": 1, "colorIndex": "neutral-1"} ] }, {"label": "sub-2", "value": 20, "colorIndex": "neutral-1"}, {"label": "sub-3", "value": 10, "colorIndex": "neutral-1"} ] }, { "label": "root-2", "value": 30, "colorIndex": "neutral-2", "children": [ {"label": "sub-4", "value": 15, "colorIndex": "neutral-2"}, {"label": "sub-5", "value": 10, "colorIndex": "neutral-1"}, {"label": "sub-6", "value": 5, "colorIndex": "neutral-3"} ] }, { "label": "root-3", "value": 20, "colorIndex": "neutral-3", "children": [ {"label": "sub-7", "value": 10, "colorIndex": "neutral-1"}, {"label": "sub-8", "value": 7, "colorIndex": "neutral-1"}, {"label": "sub-9", "value": 3, "colorIndex": "neutral-3"} ] } ]} active={[0, 0, 0]} label={<Legend series={[ { "colorIndex": "neutral-1", "label": "root-1", "value": <Value value={50} size='small' /> }, { "colorIndex": "neutral-1", "label": "sub-1", "value": <Value value={20} size='small' /> }, { "colorIndex": "neutral-1", "label": "leaf-1", "value": <Value value={5} size='small' /> } ]} />} onActive={() => {console.log("on active")}} onClick={() => {console.log("on click")}} /> <Legend series={[ {"label": "on target", "colorIndex": "neutral-1"}, {"label": "over", "colorIndex": "neutral-2"}, {"label": "under", "colorIndex": "neutral-3"} ]} /> </Box> ) } } export default MySunburst
src/index.js
connameng/router-survey-project
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import '../public/assets/css/main.css' ReactDOM.render( <App />, document.getElementById('root') ); ReactDOM.render(<App/>, document.getElementById('root'));
app/static/js/src.react/components/Profile.js
jhia/fundayacucho-social
import React from 'react'; import Post from './Post'; import Paper from 'material-ui/Paper'; import Avatar from 'material-ui/Avatar'; const Profile = React.createClass({ avatar () { return this.props.user.profile_photo ? <Avatar src={this.props.user.profile_photo} size={80} /> : <Avatar size={80}>{this.props.user.name.charAt(0).toUpperCase() + this.props.user.lastname.charAt(0).toUpperCase()}</Avatar> }, render () { return ( <section> <article> <Paper zDepth={2} style={{top: '50', left: '50', transform: 'translate(-50, -50)'}}> {this.avatar()} <h2>{`${this.props.user.name} ${this.props.user.lastname}`}</h2> <p>{this.props.user.career ? this.props.user.career : "Estudiante"} | {this.props.user.bday}</p> </Paper> </article> {this.props.posts.map((post, i) => <Post {...this.props} key={i} i={i} post={post} />)} </section> ) } }); export default Profile;
js/Details.js
mcqnyc/complete-intro-to-react
import React from 'react' import { connect } from 'react-redux' import { getOMDBDetails } from './actionCreators' import Header from './Header' const { shape, string, func } = React.PropTypes const Details = React.createClass({ propTypes: { show: shape({ title: string, year: string, poster: string, trailer: string, imdbID: string }), omdbData: shape({ imdbID: string }), dispatch: func }, componentDidMount () { if (!this.props.omdbData.imdbRating) { this.props.dispatch(getOMDBDetails(this.props.show.imdbID)) } }, render () { const { title, description, year, poster, trailer } = this.props.show let rating if (this.props.omdbData.imdbRating) { rating = <h3>{this.props.omdbData.imdbRating}</h3> } else { rating = <img src='/public/img/loading.png' alt='loading indicator' /> } return ( <div className='details'> <Header /> <section> <h1>{title}</h1> <h2>({year})</h2> {rating} <img src={`/public/img/posters/${poster}`} /> <p>{description}</p> </section> <div> <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&amp;controls=0&amp;showinfo=0`} frameBorder='0' allowFullScreen /> </div> </div> ) } }) const mapStateToProps = (state, ownProps) => { const omdbData = state.omdbData[ownProps.show.imdbID] ? state.omdbData[ownProps.show.imdbID] : {} return { omdbData } } export default connect(mapStateToProps)(Details)
src/components/Tabs.js
chiefwhitecloud/running-man-frontend
import React from 'react'; import TabHeader from './TabHeader'; export default class extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { selected: this.props.selected }; } handleClick(index) { this.setState({ selected: index, }); } renderTitles() { function labels(child, index) { return ( <TabHeader key={index} isActive={this.state.selected === index} text={child.props.label} onSelected={this.handleClick} index={index} /> ); } return ( <div className="tab-header-container"> {this.props.children.map(labels.bind(this))} </div> ); } renderContent() { return ( <div className="tab__content"> {this.props.children[this.state.selected]} </div> ); } render() { return ( <div className="tabs"> {this.renderTitles()} {this.renderContent()} </div> ); } }
app/containers/App/index.js
rahsheen/scalable-react-app
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import styles from './styles.css'; export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div className={styles.container}> {React.Children.toArray(this.props.children)} </div> ); } }
src/components/shared/PageExt/PageExt.native.js
mutualmobile/Brazos
import React, { Component } from 'react'; import { StyleSheet, Image, View, Text } from 'react-native'; import ActiveLink from '../../theme/ActiveLink'; export default platform = { render: function({navigation}) { return ( <View> <Text>Native Page View</Text> <ActiveLink navigation={navigation} to='home'></ActiveLink> </View> ); } }
src/components/auth/signout.js
SRosenshein/react-auth-client
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../actions'; class Signout extends Component { componentWillMount() { this.props.signoutUser(); } render() { return ( <div> Sorry to see you go </div> ); } } export default connect(null, actions)(Signout);
test/test_helper.js
ajdeleon/weather
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
lib/carbon-fields/vendor/htmlburger/carbon-fields/assets/js/containers/components/container/index.js
boquiabierto/wherever-content
/** * The external dependencies. */ import React from 'react'; import { branch, renderComponent } from 'recompose'; import { isObject } from 'lodash'; /** * The internal dependencies. */ import ContainerTabbed from 'containers/components/container/tabbed'; import ContainerPlain from 'containers/components/container/plain'; export default branch( ({ container }) => isObject(container.settings.tabs), renderComponent(ContainerTabbed) )(ContainerPlain);
example/src/index.js
conorhastings/react-tooltip
'use strict' import React from 'react' import ReactTooltip from '../../src/index' const Test = React.createClass({ getInitialState () { return { place: 'top', type: 'dark', effect: 'float', condition: false } }, changePlace (place) { this.setState({ place: place }) }, changeType (type) { this.setState({ type: type }) }, changeEffect (effect) { this.setState({ effect: effect }) }, _onClick () { this.setState({ condition: true }) }, render () { let { place, type, effect } = this.state return ( <section className='tooltip-example'> <h4 className='title'>React Tooltip</h4> <div className='demonstration'> <a data-tip='React-tooltip asd, a'> ◕‿‿◕ </a> </div> <div className='control-panel'> <div className='button-group'> <div className='item'> <p>Place</p> <a className={place === 'top' ? 'active' : ''} onClick={this.changePlace.bind(this, 'top')}>Top<span className='mark'>(default)</span></a> <a className={place === 'right' ? 'active' : ''} onClick={this.changePlace.bind(this, 'right')}>Right</a> <a className={place === 'bottom' ? 'active' : ''} onClick={this.changePlace.bind(this, 'bottom')}>Bottom</a> <a className={place === 'left' ? 'active' : ''} onClick={this.changePlace.bind(this, 'left')}>Left</a> </div> <div className='item'> <p>Type</p> <a className={type === 'dark' ? 'active' : ''} onClick={this.changeType.bind(this, 'dark')}>Dark<span className='mark'>(default)</span></a> <a className={type === 'success' ? 'active' : ''} onClick={this.changeType.bind(this, 'success')}>Success</a> <a className={type === 'warning' ? 'active' : ''} onClick={this.changeType.bind(this, 'warning')}>Warning</a> <a className={type === 'error' ? 'active' : ''} onClick={this.changeType.bind(this, 'error')}>Error</a> <a className={type === 'info' ? 'active' : ''} onClick={this.changeType.bind(this, 'info')}>Info</a> <a className={type === 'dlight' ? 'active' : ''} onClick={this.changeType.bind(this, 'light')}>Light</a> </div> <div className='item'> <p>Effect</p> <a className={effect === 'float' ? 'active' : ''} onClick={this.changeEffect.bind(this, 'float')}>Float<span className='mark'>(default)</span></a> <a className={effect === 'solid' ? 'active' : ''} onClick={this.changeEffect.bind(this, 'solid')}>Solid</a> </div> </div> <pre> <div> <p className='label'>Code</p> <hr></hr> <p>{'<a data-tip="React-tooltip"> ◕‿‿◕ </a>'}</p> <p>{'<ReactTooltip place="' + place + '" type="' + type + '" effect="' + effect + '"/>'}</p> </div> </pre> </div> <ReactTooltip place={place} type={type} effect={effect} /> </section> ) } }) React.render(<Test />, document.body)
modules/react-documentation/src/components/Docs.js
casesandberg/reactcss
'use strict'; import React from 'react' import reactCSS from 'reactcss' import map from 'lodash/map' import throttle from 'lodash/throttle' import markdown from '../helpers/markdown' import { Grid } from '../../../react-basic-layout' import MarkdownTitle from './MarkdownTitle' import Markdown from './Markdown' import Code from './Code' import Sidebar from './Sidebar' class Docs extends React.Component { constructor() { super(); this.state = { sidebarFixed: false, visible: false, files: {}, }; this.changeSelection = this.changeSelection.bind(this); this.attachSidebar = this.attachSidebar.bind(this); this.handleScroll = this.handleScroll.bind(this); this.handleScroll = throttle(this.handleScroll, 200); } componentDidMount() { window.addEventListener('scroll', this.handleScroll, false); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll, false); } handleScroll(e) { this.changeSelection(); this.attachSidebar(); } attachSidebar() { var sidebar = this.refs.sidebar; if (sidebar) { var sidebarTop = sidebar.getBoundingClientRect().top; if (sidebarTop <= 0 && this.state.sidebarFixed === false) { this.setState({ sidebarFixed: true }); } if (sidebarTop > 0 && this.state.sidebarFixed === true) { this.setState({ sidebarFixed: false }); } } } changeSelection() { const items = document.getElementsByClassName('file'); const doc = document.documentElement; const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); map(items, (item) => { const bottomOfItem = item.offsetTop + item.clientHeight; if (item.offsetTop < top && bottomOfItem > top) { if (this.state.visible !== item.id) { this.setState({ visible: item.id }); } } }); } render() { var markdownFiles = []; for (var fileName in this.props.markdown) { if (this.props.markdown.hasOwnProperty(fileName)) { var file = this.props.markdown[fileName]; if (file) { var args = markdown.getArgs(file); var body = markdown.getBody(file); markdownFiles.push( <div key={ fileName } id={ args.id } className="markdown file"> { args.title && !args.hideTitle && ( <MarkdownTitle isHeadline={ markdown.isSubSection(fileName) ? true : false } title={ args.title } link={ args.id } primaryColor={ this.props.primaryColor } /> ) } <Markdown>{ body }</Markdown> </div> ); } } } return ( <div> <style>{` #intro em{ font-style: normal; position: absolute; margin-top: 25px; color: #FF9800; } .rendered{ color: #607D8B; // blue grey 500 } .rendered .hljs-comment { color: #B0BEC5; // blue grey 200 } .rendered .hljs-keyword{ color: #EF9A9A; // red 200 } .rendered .hljs-string{ color: #689F38; // light green 700 } .rendered .hljs-title{ } .text code{ background: #ddd; padding: 1px 5px 3px; border-radius: 2px; box-shadow: inset 0 0 0 1px rgba(0,0,0,.03); font-size: 85%; vertical-align: bottom; } .markdown.file:last-child { min-height: 100vh; } .markdown a { color: #4A90E2; } .markdown a:visited { color: #49535B; } .markdown p{ margin: 15px 24px 15px 0; } .markdown h1{ font-size: 36px; font-weight: 200; color: rgba(0,0,0,.77); margin: 0; padding-top: 54px; padding-bottom: 5px; line-height: 46px; } .markdown h2{ font-size: 26px; line-height: 32px; font-weight: 200; color: rgba(0,0,0,.57); padding-top: 20px; margin-top: 20px; margin-bottom: 10px; } .markdown h3{ font-weight: normal; font-size: 20px; padding-top: 20px; margin-top: 20px; color: rgba(0,0,0,.67); } `}</style> { this.props.sidebar !== false ? <Grid> <div ref="sidebar"> <Sidebar files={ this.props.markdown } active={ this.state.visible } primaryColor={ this.props.primaryColor } bottom={ this.props.bottom } fixed={ this.state.sidebarFixed } /> </div> <div ref="files"> { markdownFiles } </div> </Grid> : <div ref="files"> { markdownFiles } </div> } </div> ); } } Docs.defaultProps = { primaryColor: '#03A9F4', }; module.exports = Docs;
1-appYoutube/src/components/video_detail.js
OscarDeDios/cursoUdemyReact
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;