path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/components/Feed/presenter.js
plusbeauxjours/nomadgram
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.scss'; import Loading from 'components/Loading'; import FeedPhoto from 'components/FeedPhoto'; const Feed = props => { if(props.loading){ return <LoadingFeed />; } else if (props.feed){ return <RenderFeed {...props} /> } }; const LoadingFeed = props => ( <div className={styles.feed}> <Loading /> </div> ); const RenderFeed = props => ( <div className={styles.feed}> {props.feed.map(photo => <FeedPhoto {...photo} key={photo.id} /> )} </div> ) Feed.propTypes = { loading: PropTypes.bool.isRequired, feed: PropTypes.array }; RenderFeed.propTypes = { feed: PropTypes.array } export default Feed;
src/app/components/TodoApp/TodoApp.js
batazor/LMap
import React from 'react' // eslint-disable-line no-unused-vars import Footer from './Footer' import AddTodo from '../../containers/AddTodo' import VisibleTodoList from '../../containers/VisibleTodoList' const Todo = () => ( <div> <AddTodo /> <VisibleTodoList /> <Footer /> </div> ) export default Todo
app/components/About.js
chena/kiminonawa-web
import React from 'react'; import Container from 'muicss/lib/react/container'; import Divider from 'muicss/lib/react/divider'; import Row from 'muicss/lib/react/row'; import Col from 'muicss/lib/react/col'; import styles from '../styles.css'; import taiwanIcon from '../images/taiwan_icon.png'; export default class About extends React.Component { render() { return ( <div> <Container className={styles.pageBody}> <Row className={styles.pageTop}> <Col md="4" md-offset="4"> <img src={taiwanIcon} className={styles.icon} /> <h3 className={styles.heading}>關於正名</h3> <p className={styles.bodyText}> 以下提供關於台灣正名相關資訊 </p> </Col> </Row> <Row> <Col md="8" md-offset="2"> <div className={styles.greenDivider} /> </Col> </Row> <Row> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>為什麼我們不喜歡Taiwan, Province of China?</h3> <p className={styles.bodyText}>Taiwan, Province of China暗指台灣是中國的一省。但以目前狀況(de facto)來說,台灣並非為中國的一省,而是與中國不同的兩個主權。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>中國聲稱台灣是中國的一省,是否合理?</h3> <p className={styles.bodyText}>事實上並不合理。台灣的歷史大概可概分為:</p> <ol> <li>史前時期</li> <li>荷蘭時期</li> <li>明鄭時期</li> <li>清領時期</li> <li>日治時期</li> <li>中華民國統治時期</li> </ol> <p>其中,台灣被中國方面政權統治僅只有清領時期與中華民國統治時期,共XX年,僅佔台灣歷史XX%。</p> <p>因此,中國方面聲稱台灣是中國的一部分,事實上並不合理。</p> <p>如果台灣不屬於中國,為何國名寫「Republic of China」?</p> <p>Republic of China是中華民國的國名。在中國清朝結束統治後,將政府改制為民主政府,國名為中華民國,英文名稱為Republic of China。</p> <p>在1945年二次世界大戰結束後,由於日本放棄臺灣的統治權,因此台灣地區被中華民國接收代管。</p> <p>但在1949年,由於中國共產黨不喜歡當時的統治者國民黨,因此在當時蘇俄支持下聚集軍事力量,推翻當時國民黨於中國地區的政權。當時國民黨將剩餘的資源聚集起來運往台灣,希望能從台灣聚集力量後,重新發起戰爭,收回中國地區的失土。</p> <p>但在經過幾十年的演變後,目前中華民國已無能力重新開啟內戰;但中國卻聲稱台灣屬於中國,其實並不合理。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>所謂的一中原則究竟是什麼?</h3> <p className={styles.bodyText}>過往,台灣的國民黨政權堅持「中國只有一個」,而共產黨也堅持「中國只有一個」,因此在1992年時,雙方進行了會談。雖然會談上沒有談出共識,但在xxxx年,因為選舉的需要,??喊出了「九二共識」,對台灣方面來說,這個共識是「一個中國,各自表述」,但中國卻堅持其中的「一個中國」,並堅持他們是唯一的正統代理。事實上,台灣(中華民國)與中國只是中國土地上不同時期的統治者,兩者並不相同。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>台灣人是中國人嗎?</h3> <p className={styles.bodyText}>A根據台灣2016年最新兩份民調結果顯示,聯合報民調僅有一成比例之台灣民眾認為自己也是中國人,七成三的台灣民眾認為是自己是台灣人。新國策智庫民調則指出,八成六台灣民眾認為自己是台灣人,僅有近7%比例的民眾認為自己是中國人。</p> <p>由於中國的政權並非民主政體,因此台灣人也不希望被中國統一。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>我們該怎麼辦</h3> <p className={styles.bodyText}>請幫忙把Taiwan, Province of China改為Taiwan即可。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>我們是follow聯合國的命名(ISOxxx)原則,真的可以改嗎?</h3> <p className={styles.bodyText}>有另外一個命名原則與這個不一樣,是ISOxxx,可以參照這個原則,會對台灣更友善。謝謝!</p> <div className={styles.letterBox}> <p>Dear Sir or Madam,</p> <p>It seems your web service is using the country list with the ISO3166-2 list.</p> <p>It is advised to use country names in the GENC[1] standard (formly known as FIPS 10-4) to avoid controversy of Taiwan and to be able to include Kosovo.</p> <p>[1] https://www.fgdc.gov/standards/news/GENC</p> </div> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>如果改名以後,中國的使用者生氣怎麼辦?</h3> <p className={styles.bodyText}>一個國家的認同不應該取決於其他國家人民的喜好。</p> </div> </Col> <Col md="8" md-offset="2"> <div className={styles.aboutSection}> <h3 className={styles.staffCardHeading}>相關資料</h3> <p className={styles.bodyText}>資料1: 老外看兩岸關係(經典影片重製)</p> <style>{"\ .video-container {\ position:relative;\ padding-bottom:56.25%;\ padding-top:30px;\ height:0;\ overflow:hidden;\ }\ .video-container iframe, .video-container object, .video-container embed {\ position:absolute;\ top:0;\ left:0;\ width:100%;\ height:100%;\ }\ "}</style> <div className="video-container"><iframe width="560" height="315" src="https://www.youtube.com/embed/PCaJiNjyjDk" frameborder="0" allowfullscreen></iframe></div> <p className={styles.bodyText}>資料2: <a href="https://zh.wikipedia.org/wiki/%E5%8F%B0%E7%81%A3%E6%AD%B7%E5%8F%B2" target="_blank">臺灣歷史Wiki</a></p> </div> </Col> </Row> </Container> </div> ); } }
webpack/ForemanTasks/Components/TasksTable/SubTasksPage.js
adamruzicka/foreman-tasks
import React from 'react'; import PropTypes from 'prop-types'; import { sprintf, translate as __ } from 'foremanReact/common/I18n'; import TasksTablePage from './'; export const SubTasksPage = props => { const parentTaskID = props.match.params.id; const getBreadcrumbs = actionName => ({ breadcrumbItems: [ { caption: __('Tasks'), url: `/foreman_tasks/tasks` }, { caption: actionName, url: `/foreman_tasks/tasks/${parentTaskID}`, }, { caption: __('Sub tasks') }, ], }); const createHeader = actionName => actionName ? sprintf(__('Sub tasks of %s'), actionName) : __('Sub tasks'); return ( <TasksTablePage getBreadcrumbs={getBreadcrumbs} parentTaskID={parentTaskID} createHeader={createHeader} {...props} /> ); }; SubTasksPage.propTypes = { match: PropTypes.shape({ params: PropTypes.object, }), }; SubTasksPage.defaultProps = { match: { params: {}, }, };
docs/app/Examples/elements/Image/Groups/index.js
vageeshb/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ImageTypesExamples = () => ( <ExampleSection title='Groups'> <ComponentExample title='Size' description='A group of images can be formatted to have the same size.' examplePath='elements/Image/Groups/ImageExampleGroupSize' /> </ExampleSection> ) export default ImageTypesExamples
src/parser/ui/Cooldown.js
anom0ly/WoWAnalyzer
import { Trans } from '@lingui/macro'; import { formatThousands, formatNumber, formatPercentage, formatDuration } from 'common/format'; import SPELLS from 'common/SPELLS'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; import { Icon, SpellLink } from 'interface'; import { TooltipElement } from 'interface'; import { EventType } from 'parser/core/Events'; import { BUILT_IN_SUMMARY_TYPES } from 'parser/shared/modules/CooldownThroughputTracker'; import PropTypes from 'prop-types'; import React from 'react'; import './Cooldown.css'; class Cooldown extends React.Component { static propTypes = { fightStart: PropTypes.number.isRequired, fightEnd: PropTypes.number.isRequired, cooldown: PropTypes.shape({ ability: PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, }), start: PropTypes.number.isRequired, end: PropTypes.number, events: PropTypes.arrayOf( PropTypes.shape({ type: PropTypes.string.isRequired, }), ).isRequired, summary: PropTypes.array.isRequired, spell: PropTypes.shape({ id: PropTypes.number, icon: PropTypes.string, name: PropTypes.string, }), }).isRequired, applyTimeFilter: PropTypes.func, }; constructor() { super(); this.state = { showCastEvents: false, showAllEvents: false, }; this.handleExpandClick = this.handleExpandClick.bind(this); this.handleShowHealsClick = this.handleShowHealsClick.bind(this); } handleExpandClick() { this.setState({ showCastEvents: !this.state.showCastEvents, showAllEvents: false, }); } handleShowHealsClick() { this.setState({ showAllEvents: !this.state.showAllEvents, }); } groupHeals(events) { let lastHeal = null; return events.reduce((results, event) => { if (event.type === EventType.Cast) { results.push(event); } else if (event.type === EventType.Heal) { const spellId = event.ability.guid; if (lastHeal && lastHeal.event.ability.guid === spellId) { lastHeal.count += 1; lastHeal.amount += event.amount; lastHeal.absorbed += event.absorbed || 0; lastHeal.overheal += event.overheal || 0; } else { const heal = { event, amount: event.amount, absorbed: event.absorbed || 0, overheal: event.overheal || 0, count: 1, }; results.push(heal); lastHeal = heal; } } return results; }, []); } calculateHealingStatistics(cooldown) { let healingDone = 0; let overhealingDone = 0; cooldown.events .filter((event) => event.type === EventType.Heal || event.type === EventType.Absorbed) .forEach((event) => { healingDone += event.amount + (event.absorbed || 0); overhealingDone += event.overheal || 0; }); return { healingDone, overhealingDone, }; } calculateDamageStatistics(cooldown) { const damageDone = cooldown.events.reduce( (acc, event) => event.type === EventType.Damage ? acc + ((event.amount || 0) + (event.absorbed || 0)) : acc, 0, ); return { damageDone }; } render() { const { cooldown, fightStart, fightEnd } = this.props; let healingStatistics = null; const start = cooldown.start; const end = cooldown.end || fightEnd; /* eslint-disable no-script-url */ /* eslint-disable jsx-a11y/anchor-is-valid */ return ( <article> <figure> <SpellLink id={cooldown.spell.id} icon={false}> <Icon icon={cooldown.spell.icon} alt={cooldown.spell.name} /> </SpellLink> </figure> <div className="row" style={{ width: '100%' }}> <div className={this.state.showAllEvents ? 'col-md-12' : 'col-md-6'}> <header style={{ marginTop: 5, fontSize: '1.25em', marginBottom: '.1em' }}> <SpellLink id={cooldown.spell.id} icon={false} /> ( {formatDuration((start - fightStart) / 1000)} -&gt;{' '} {formatDuration((end - fightStart) / 1000)}) &nbsp; <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.events.tooltip"> Filter events to the cooldown window. </Trans> } > <a href="javascript:" onClick={() => this.props.applyTimeFilter(start - fightStart, end - fightStart)} > <Trans id="shared.cooldownThroughputTracker.cooldown.events">Filter events</Trans> </a> </TooltipElement> </header> {!this.state.showCastEvents && ( <div> {cooldown.events .filter((event) => event.type === EventType.Cast && event.ability.guid !== 1) .map((event, i) => ( <SpellLink key={`${event.ability.guid}-${event.timestamp}-${i}`} id={event.ability.guid} icon={false} > <Icon icon={event.ability.abilityIcon} alt={event.ability.name} style={{ height: 23, marginRight: 4 }} /> </SpellLink> ))} <div className="row"> <div className="col-xs-12"> {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} <a href="javascript:void(0)" onClick={this.handleExpandClick} style={{ marginTop: '.2em' }} > <Trans id="shared.cooldownThroughputTracker.cooldown.expand">More</Trans> </a> </div> </div> </div> )} {this.state.showCastEvents && !this.state.showAllEvents && ( <div className="container-fluid"> {cooldown.events .filter((event) => event.type === EventType.Cast && event.ability.guid !== 1) .map((event, i) => ( <div className="row" key={i}> <div className="col-xs-2 text-right" style={{ padding: 0 }}> +{((event.timestamp - cooldown.start) / 1000).toFixed(3)} </div> <div className="col-xs-10"> <SpellLink key={`${event.ability.guid}-${event.timestamp}-${i}`} id={event.ability.guid} icon={false} > <Icon icon={event.ability.abilityIcon} alt={event.ability.name} style={{ height: 23, marginRight: 4 }} />{' '} {event.ability.name} </SpellLink> </div> </div> ))} <div className="row"> <div className="col-xs-12"> <a href="javascript:" onClick={this.handleShowHealsClick} style={{ marginTop: '.2em' }} > <Trans id="shared.cooldownThroughputTracker.cooldown.expand.again"> Even more </Trans> </a> {' | '} {/* eslint-disable-line jsx-a11y/anchor-is-valid */} <a href="javascript:" onClick={this.handleExpandClick} style={{ marginTop: '.2em' }} > <Trans id="shared.cooldownThroughputTracker.cooldown.shrink">Show less</Trans> </a> {/* eslint-disable-line jsx-a11y/anchor-is-valid */} </div> </div> </div> )} {this.state.showCastEvents && this.state.showAllEvents && ( <div className="container-fluid"> {this.groupHeals( cooldown.events.filter( (event) => (event.type === EventType.Cast || event.type === EventType.Heal) && event.ability.guid !== 1, ), ).map((heal, i) => { const event = heal.event || heal; return ( <div className="row" key={i}> <div className="col-xs-1 text-right" style={{ padding: 0 }}> +{((event.timestamp - cooldown.start) / 1000).toFixed(3)} </div> <div className={`col-xs-4 ${ event.type === EventType.Heal ? 'col-xs-offset-1' : '' }`} > <SpellLink key={`${event.ability.guid}-${event.timestamp}-${i}`} id={event.ability.guid} icon={false} > <Icon icon={event.ability.abilityIcon} alt={event.ability.name} style={{ height: 23, marginRight: 4 }} />{' '} {event.ability.name} </SpellLink> {event.type === EventType.Heal && ( <span> <span className="grouped-heal-meta amount"> x {heal.count}</span> </span> )} </div> {event.type === EventType.Heal && ( <div className="col-xs-4"> <span className="grouped-heal-meta healing"> {' '} +{formatThousands(heal.amount + heal.absorbed)} </span> <span className="grouped-heal-meta overhealing"> {' '} (O: {formatThousands(heal.overheal)}) </span> </div> )} </div> ); })} <a href="javascript:" onClick={this.handleShowHealsClick} style={{ marginTop: '.2em' }} > <Trans id="shared.cooldownThroughputTracker.cooldown.shrink">Show less</Trans> </a> {' | '} {/* eslint-disable-line jsx-a11y/anchor-is-valid */} <a href="javascript:" onClick={this.handleExpandClick} style={{ marginTop: '.2em' }} > <Trans id="shared.cooldownThroughputTracker.cooldown.simple">Show simple</Trans> </a> {/* eslint-disable-line jsx-a11y/anchor-is-valid */} </div> )} </div> {!this.state.showAllEvents && ( <div className="col-md-6"> <div className="row"> {cooldown.summary.map((item) => { switch (item) { case BUILT_IN_SUMMARY_TYPES.HEALING: healingStatistics = healingStatistics || this.calculateHealingStatistics(cooldown); return ( <div className="col-md-4 text-center" key="healing"> <div style={{ fontSize: '2em' }}> {formatNumber(healingStatistics.healingDone)} </div> <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.healing.tooltip"> This includes all healing that occured while the buff was up, even if it was not triggered by spells cast inside the buff duration. Any delayed healing such as HOTs, Absorbs and Atonements will stop contributing to the healing done when the cooldown buff expires, so this value is lower for any specs with such abilities. </Trans> } > <Trans id="shared.cooldownThroughputTracker.cooldown.healing"> healing ( {formatNumber((healingStatistics.healingDone / (end - start)) * 1000)}{' '} HPS) </Trans> </TooltipElement> </div> ); case BUILT_IN_SUMMARY_TYPES.OVERHEALING: healingStatistics = healingStatistics || this.calculateHealingStatistics(cooldown); return ( <div className="col-md-4 text-center" key="overhealing"> <div style={{ fontSize: '2em' }}> {formatPercentage( healingStatistics.overhealingDone / (healingStatistics.healingDone + healingStatistics.overhealingDone), )} % </div> <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.overhealing.tooltip"> This includes all healing that occured while the buff was up, even if it was not triggered by spells cast inside the buff duration. Any delayed healing such as HOTs, Absorbs and Atonements will stop contributing to the healing done when the cooldown buff expires, so this value is lower for any specs with such abilities. </Trans> } > <Trans id="shared.cooldownThroughputTracker.cooldown.overhealing"> overhealing </Trans> </TooltipElement> </div> ); case BUILT_IN_SUMMARY_TYPES.ABSORBED: { const total = cooldown.events .filter((event) => event.type === EventType.Absorbed) .reduce((total, event) => total + (event.amount || 0), 0); return ( <div className="col-md-4 text-center" key="absorbed"> <div style={{ fontSize: '2em' }}>{formatNumber(total)}</div> <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.absorbed.tooltip"> This includes all damage absorbed that occured while the buff was up, even if it was not triggered by spells cast inside the buff duration. </Trans> } > <Trans id="shared.cooldownThroughputTracker.cooldown.absorbed"> damage absorbed </Trans> </TooltipElement> </div> ); } case BUILT_IN_SUMMARY_TYPES.ABSORBS_APPLIED: { const total = cooldown.events .filter((event) => event.type === EventType.ApplyBuff) .reduce((total, event) => total + (event.absorb || 0), 0); return ( <div className="col-md-4 text-center" key="absorbs-applied"> <div style={{ fontSize: '2em' }}>{formatNumber(total)}</div> <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.absorbApplied.tooltip"> The total amount of absorb shields applied during the buff. </Trans> } > <Trans id="shared.cooldownThroughputTracker.cooldown.absorbApplied"> absorb applied </Trans> </TooltipElement> </div> ); } case BUILT_IN_SUMMARY_TYPES.MANA: { let manaUsed = 0; if (cooldown.spell.id === SPELLS.INNERVATE.id) { manaUsed = cooldown.events .filter((event) => event.type === EventType.Cast) .reduce( (total, event) => total + (event.rawResourceCost[RESOURCE_TYPES.MANA.id] || 0), 0, ); } else { manaUsed = cooldown.events .filter((event) => event.type === EventType.Cast) .reduce( (total, event) => total + (event.resourceCost[RESOURCE_TYPES.MANA.id] || 0), 0, ); } return ( <div> <Trans id="shared.cooldownThroughputTracker.cooldown.manaUsed" className="col-md-4 text-center" key="mana" > <div style={{ fontSize: '2em' }}>{formatNumber(manaUsed)}</div> mana used </Trans> </div> ); } case BUILT_IN_SUMMARY_TYPES.DAMAGE: { const damageStatistics = this.calculateDamageStatistics(cooldown); return ( <div className="col-md-4 text-center" key="damage"> <div style={{ fontSize: '2em' }}> {formatNumber(damageStatistics.damageDone)} </div> <TooltipElement content={ <Trans id="shared.cooldownThroughputTracker.cooldown.damageDone.tooltip"> This number represents the total amount of damage done during the duration of this cooldown, any damage done by DOTs after the effect of this cooldown has exprired will not be included in this statistic. </Trans> } > <Trans id="shared.cooldownThroughputTracker.cooldown.damageDone"> damage ( {formatNumber((damageStatistics.damageDone / (end - start)) * 1000)}{' '} DPS) </Trans> </TooltipElement> </div> ); } default: // Custom return ( <div className="col-md-4 text-center" key={item.label}> <div style={{ fontSize: '2em' }}> {typeof item.value === 'string' ? item.value : formatNumber(item.value)} </div> <TooltipElement content={item.tooltip}>{item.label}</TooltipElement> </div> ); } })} </div> </div> )} </div> </article> ); } } export default Cooldown;
server/sonar-web/src/main/js/apps/overview/gate/gate-condition.js
joansmith/sonarqube
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { getPeriodLabel, getPeriodDate } from '../helpers/periods'; import { DrilldownLink } from '../../../components/shared/drilldown-link'; import { formatMeasure } from '../../../helpers/measures'; import { translate } from '../../../helpers/l10n'; const Measure = React.createClass({ render() { if (this.props.value == null || isNaN(this.props.value)) { return null; } let formatted = formatMeasure(this.props.value, this.props.type); return <span>{formatted}</span>; } }); export default React.createClass({ render() { let metricName = translate('metric', this.props.condition.metric.name, 'name'); let threshold = this.props.condition.level === 'ERROR' ? this.props.condition.error : this.props.condition.warning; let period = this.props.condition.period ? getPeriodLabel(this.props.component.periods, this.props.condition.period) : null; let periodDate = getPeriodDate(this.props.component.periods, this.props.condition.period); let classes = 'alert_' + this.props.condition.level.toUpperCase(); return ( <li className="overview-gate-condition"> <div className="little-spacer-bottom">{period}</div> <div style={{ display: 'flex', alignItems: 'center' }}> <div className="overview-gate-condition-value"> <DrilldownLink component={this.props.component.key} metric={this.props.condition.metric.name} period={this.props.condition.period} periodDate={periodDate}> <span className={classes}> <Measure value={this.props.condition.actual} type={this.props.condition.metric.type}/> </span> </DrilldownLink>&nbsp; </div> <div className="overview-gate-condition-metric"> <div>{metricName}</div> <div> {translate('quality_gates.operator', this.props.condition.op, 'short')} {' '} <Measure value={threshold} type={this.props.condition.metric.type}/> </div> </div> </div> </li> ); } });
src/components/events.js
Diane27/big-red-hacks-2017
import React from 'react'; import { Switch, Route } from 'react-router-dom' import AllEvents from './events/all_events'; import EventDetails from './events/event_details' const Events = () => ( <Switch> <Route exact path='/events' component={AllEvents}/> <Route path='/events/:eventId' component={EventDetails}/> </Switch> ) export default Events
src/component/dashboard-container/index.js
saidmattar/cloud-life-frontend
import './_dashboard-container.scss'; import React from 'react'; import {connect} from 'react-redux'; import DocumentForm from '../document-form'; import DocumentContainer from '../document-container'; import GroupContainer from '../group-container'; import {groupFetchRequest} from '../../action/group-actions.js'; import {profileFetchRequest} from '../../action/profile-actions'; import {docCreateRequest, docsFetchRequest} from '../../action/document-actions.js'; import * as utils from '../../lib/utils'; class DashboardContainer extends React.Component { componentWillMount() { this.props.docsFetch(); this.props.groupFetch(); this.props.profileFetch(); } render() { return ( <div className="dashboard-container"> <h2>Upload Your Documents</h2> <DocumentForm /> <h2 className="somepadding">Your Uploaded Documents</h2> <DocumentContainer /> </div> ); } } let mapStateToProps = state => ({ docs: state.docs, }); let mapDispatchToProps = dispatch => ({ docsFetch: () => dispatch(docsFetchRequest()), groupFetch: () => dispatch(groupFetchRequest()), profileFetch: () => dispatch(profileFetchRequest()), docCreate: doc => dispatch(docCreateRequest(doc)), }); export default connect(mapStateToProps, mapDispatchToProps)(DashboardContainer);
app/javascript/mastodon/components/intersection_observer_article.js
pfm-eyesightjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import scheduleIdleTask from '../features/ui/util/schedule_idle_task'; import getRectFromEntry from '../features/ui/util/get_rect_from_entry'; export default class IntersectionObserverArticle extends ImmutablePureComponent { static propTypes = { intersectionObserverWrapper: PropTypes.object, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), children: PropTypes.node, }; state = { isHidden: false, // set to true in requestIdleCallback to trigger un-render } shouldComponentUpdate (nextProps, nextState) { if (!nextState.isIntersecting && nextState.isHidden) { // It's only if we're not intersecting (i.e. offscreen) and isHidden is true // that either "isIntersecting" or "isHidden" matter, and then they're // the only things that matter (and updated ARIA attributes). return this.state.isIntersecting || !this.state.isHidden || nextProps.listLength !== this.props.listLength; } else if (nextState.isIntersecting && !this.state.isIntersecting) { // If we're going from a non-intersecting state to an intersecting state, // (i.e. offscreen to onscreen), then we definitely need to re-render return true; } // Otherwise, diff based on "updateOnProps" and "updateOnStates" return super.shouldComponentUpdate(nextProps, nextState); } componentDidMount () { if (!this.props.intersectionObserverWrapper) { // TODO: enable IntersectionObserver optimization for notification statuses. // These are managed in notifications/index.js rather than status_list.js return; } this.props.intersectionObserverWrapper.observe( this.props.id, this.node, this.handleIntersection ); this.componentMounted = true; } componentWillUnmount () { if (this.props.intersectionObserverWrapper) { this.props.intersectionObserverWrapper.unobserve(this.props.id, this.node); } this.componentMounted = false; } handleIntersection = (entry) => { if (this.node && this.node.children.length !== 0) { // save the height of the fully-rendered element this.height = getRectFromEntry(entry).height; if (this.props.onHeightChange) { this.props.onHeightChange(this.props.status, this.height); } } this.setState((prevState) => { if (prevState.isIntersecting && !entry.isIntersecting) { scheduleIdleTask(this.hideIfNotIntersecting); } return { isIntersecting: entry.isIntersecting, isHidden: false, }; }); } hideIfNotIntersecting = () => { if (!this.componentMounted) { return; } // When the browser gets a chance, test if we're still not intersecting, // and if so, set our isHidden to true to trigger an unrender. The point of // this is to save DOM nodes and avoid using up too much memory. // See: https://github.com/tootsuite/mastodon/issues/2900 this.setState((prevState) => ({ isHidden: !prevState.isIntersecting })); } handleRef = (node) => { this.node = node; } render () { const { children, id, index, listLength } = this.props; const { isIntersecting, isHidden } = this.state; if (!isIntersecting && isHidden) { return ( <article ref={this.handleRef} aria-posinset={index} aria-setsize={listLength} style={{ height: `${this.height}px`, opacity: 0, overflow: 'hidden' }} data-id={id} tabIndex='0' > {children && React.cloneElement(children, { hidden: true })} </article> ); } return ( <article ref={this.handleRef} aria-posinset={index} aria-setsize={listLength} data-id={id} tabIndex='0'> {children && React.cloneElement(children, { hidden: false })} </article> ); } }
src/components/Tos/Print/PrintView.js
City-of-Helsinki/helerm-ui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators, compose } from 'redux'; import { withRouter, Link } from 'react-router-dom'; import { push } from 'connected-react-router'; import get from 'lodash/get'; import { fetchTOS } from '../../../components/Tos/reducer'; import { setNavigationVisibility } from '../../Navigation/reducer'; import { getStatusLabel, formatDateTime, getNewPath, itemById } from '../../../utils/helpers'; import MetaDataTable from './MetaDataTable'; import PrintClassification from './PrintClassification'; import PrintPhase from './PrintPhase'; import './PrintView.scss'; class PrintView extends Component { static BODY_CLASS = 'helerm-tos-print-view'; componentDidMount() { const { fetchTOS, TOS, match } = this.props; this.addBodyClass(); if (match && match.path === '/view-tos/:id/print') { this.props.setNavigationVisibility(false); } const tosAvailable = TOS.id === match.params.id && (!match.params.version || TOS.version === match.params.version); if (!tosAvailable) { let params = {}; if (typeof version !== 'undefined') { params.version = match.params.version; } fetchTOS(match.params.id, params).catch((err) => { if (err instanceof URIError) { // We have a 404 from API this.props.push(`/404?tos-id=${match.params.id}`); } }); } } componentWillUnmount() { this.removeBodyClass(); } addBodyClass() { if (document.body) { document.body.className = document.body.className + PrintView.BODY_CLASS; } } removeBodyClass() { if (document.body) { document.body.className = document.body.className.replace( PrintView.BODY_CLASS, '' ); } } render() { const { TOS, classification, getAttributeName, sortAttributeKeys, location } = this.props; if (!TOS.id) return null; return ( <article> <header> <div className="no-print btn-group"> <Link className="btn btn-primary" to={getNewPath(location.pathname, '..')} > Takaisin </Link> </div> <table className="no-border"> <tbody> <tr> <th scope="row"> <h1>{TOS.function_id}</h1> </th> <td> <h1>{TOS.name}</h1> </td> </tr> </tbody> </table> </header> <MetaDataTable rows={[ ['Tila', getStatusLabel(TOS.state)], ['Muokkausajankohta', formatDateTime(TOS.modified_at)], ['Muokkaaja', TOS.modified_by], [ 'Voimassaolo alkaa', TOS.valid_from ? formatDateTime(TOS.valid_from, 'DD.MM.YYYY') : '' ], [ 'Voimassaolo päättyy', TOS.valid_to ? formatDateTime(TOS.valid_to, 'DD.MM.YYYY') : '' ] ]} /> {classification && ( <PrintClassification classification={classification} /> )} <section> <header> <h2>Käsittelyprosessin tiedot</h2> </header> <MetaDataTable rows={[ ...sortAttributeKeys(Object.keys(TOS.attributes)).map((key) => [ getAttributeName(key), TOS.attributes[key] ]) ]} /> </section> {Object.keys(TOS.phases).map((key) => ( <PrintPhase key={TOS.phases[key].id} phase={TOS.phases[key]} getAttributeName={getAttributeName} sortAttributeKeys={sortAttributeKeys} /> ))} </article> ); } } PrintView.propTypes = { TOS: PropTypes.object, classification: PropTypes.object, fetchTOS: PropTypes.func.isRequired, getAttributeName: PropTypes.func.isRequired, location: PropTypes.object.isRequired, params: PropTypes.object, push: PropTypes.func.isRequired, sortAttributeKeys: PropTypes.func.isRequired }; const denormalizeTOS = (tos) => ({ ...tos, phases: Object.values(tos.phases) .sort((a, b) => a.index - b.inded) .map((phase) => ({ ...phase, actions: phase.actions.map((actionKey) => { const action = tos.actions[actionKey]; return { ...action, records: action.records.map((recordKey) => tos.records[recordKey]) }; }) })) }); const getClassification = (tos, items) => { if (tos && tos.classification && items) { return itemById(items, tos.classification.id); } return null; }; const mapStateToProps = (state) => ({ TOS: denormalizeTOS(state.selectedTOS), getAttributeName: (key) => get(state.ui.attributeTypes, [key, 'name'], key), classification: getClassification(state.selectedTOS, state.navigation.items), sortAttributeKeys: (keys) => keys.sort( (a, b) => get(state.ui.attributeTypes, [a, 'index'], Infinity) - get(state.ui.attributeTypes, [b, 'index'], Infinity) ) }); const mapDispatchToProps = (dispatch) => ({ fetchTOS: bindActionCreators(fetchTOS, dispatch), push: (path) => dispatch(push(path)), setNavigationVisibility: bindActionCreators(setNavigationVisibility, dispatch) }); export default compose( withRouter, connect(mapStateToProps, mapDispatchToProps) )(PrintView);
src/components/matchBets/MatchInfo.js
jahuk/bet-platform-react
import React from 'react'; const MatchInfo = ({home, away, result}) => { return ( <div className="alert alert-dismissible alert-info"> <strong>{home} VS {away}</strong> <br/>score: {result} </div> ); }; MatchInfo.propTypes = { home: React.PropTypes.string, away: React.PropTypes.string, result: React.PropTypes.string }; export default MatchInfo;
src/components/LanguageSwitcher/LanguageSwitcher.js
malinowsky/dataroot_03
/* eslint-disable no-shadow */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { setLocale } from '../../actions/intl'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './LanguageSwitcher.scss'; function LanguageSwitcher({ currentLocale, availableLocales, setLocale }) { const isSelected = locale => locale === currentLocale; const localeDict = { 'uk-UA': 'УКР', 'ru-RU': 'РУС', }; const localeName = locale => localeDict[locale] || locale; return ( <div className={s.lang_switcher}> {availableLocales.map(locale => ( <span className={s.lang_items} key={locale}> {isSelected(locale) ? ( <span className={s.lang_item}>{localeName(locale)}</span> ) : ( // github.com/yannickcr/eslint-plugin-react/issues/945 // eslint-disable-next-line react/jsx-indent <a className={s.lang_link} href={`?lang=${locale}`} onClick={(e) => { setLocale({ locale }); e.preventDefault(); }} >{localeName(locale)}</a> )} {' '} </span> ))} </div> ); } LanguageSwitcher.propTypes = { currentLocale: PropTypes.string.isRequired, availableLocales: PropTypes.arrayOf(PropTypes.string).isRequired, setLocale: PropTypes.func.isRequired, }; const mapState = state => ({ availableLocales: state.runtime.availableLocales, currentLocale: state.intl.locale, }); const mapDispatch = { setLocale, }; export default connect(mapState, mapDispatch)(withStyles(s)(LanguageSwitcher));
admin/client/App/elemental/Modal/body.js
ratecity/keystone
import React from 'react'; import { css } from 'glamor'; import theme from '../../../theme'; function ModalBody ({ className, ...props }) { return ( <div className={css(classes.body, className)} {...props} /> ); }; const classes = { body: { paddingBottom: theme.modal.padding.body.vertical, paddingLeft: theme.modal.padding.body.horizontal, paddingRight: theme.modal.padding.body.horizontal, paddingTop: theme.modal.padding.body.vertical, height: '40vh', overflowY: 'scroll', }, }; module.exports = ModalBody;
stories/decorators/wrapStory.js
isogon/material-components
import styled, { injectGlobal } from 'styled-components' import React from 'react' import { Theme, initGlobals, createTheme, colors } from '../../src' initGlobals({ fontObserver: 'Roboto' }) const theme = createTheme({ colorPrimary: colors.indigo[500], colorPirmaryDark: colors.indigo[700], colorAccent: colors.pink[500], }) // eslint-disable-next-line no-unused-expressions injectGlobal` html, body, #root { height: 100%; } body { height: calc(100% - 16px); } ` const Wrap = styled.div` height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; position: relative; ` const StoryWrap = (props) => ( <Theme theme={theme}> <Wrap>{props.children}</Wrap> </Theme> ) export default (fn) => <StoryWrap>{fn()}</StoryWrap>
src/components/Dashboard/PieGraphs/PieGraph.js
GovWizely/steel-search
import React from 'react'; import PropTypes from 'prop-types'; import { values, pickBy, has, omit, map, startCase, pick, remove } from '../../../utils/lodash'; import moment from 'moment'; import { Pie } from 'react-chartjs-2'; import { PieColors } from '../GraphColors'; import config from '../../../config'; const PieGraph = ({ data_values, labels, time_period}) => { const datasets = [ { label: startCase(time_period), fill: false, backgroundColor: PieColors, data: data_values } ]; const chartData = { labels: labels, datasets: datasets }; const chartOptions = { title: { display: false }, legend: { display: true, position: 'right', onClick: function(e){ e.stopPropagation(); }, labels: { generateLabels: function(chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { var meta = chart.getDatasetMeta(0); var ds = data.datasets[0]; var arc = meta.data[i]; var custom = arc && arc.custom || {}; var getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault; var arcOpts = chart.options.elements.arc; var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor); var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor); var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth); var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index]; return { text: label + ': ' + value + '%', fillStyle: fill, strokeStyle: stroke, lineWidth: bw, hidden: isNaN(ds.data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i }; }); } return []; } } }, tooltips: { callbacks: { label: function(tooltipItem, data){ var index = tooltipItem.index; return data.labels[index] + ': ' + data.datasets[0].data[index] + '%'; } } }, maintainAspectRatio: true }; return ( <div className="explorer__pie-graph"> <Pie data={chartData} options={chartOptions} /> </div> ); }; export default PieGraph;
src/view/dialog/resetPassword.js
VisitingLandmarks/visitingLandmarks
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {injectIntl, intlShape} from 'react-intl'; import DialogUserPassword from './userPassword'; import {resetPasswordThunk, resettingPassword} from '../../redux/action/thunk/resetPassword'; import {navigateTo} from '../../redux/action/ui'; import {failure, inProgress, success} from '../../redux/reducer/communication'; import {routes} from '../../modules/routes'; class ResetPassword extends React.Component { render () { // @todo: display nicer feedback // @todo: this will prevent the dialog from reopening - all commuication thunks should go into initial state when done. if (this.props.done) { return null; } return ( <DialogUserPassword {...this.props} open dialogName={this.props.intl.formatMessage({id: 'dialog.resetPassword.title'})} showPasswordLine={false} onSubmit={this.props.requestResetPassword} /> ); } } ResetPassword.propTypes = { done: PropTypes.bool.isRequired, onCloseDialog: PropTypes.func.isRequired, requestResetPassword: PropTypes.func.isRequired, intl: intlShape.isRequired, }; const mapStateToProps = (state) => { return { done: state.communication[resettingPassword][success] || false, disabled: state.communication[resettingPassword][inProgress] || false, error: state.communication[resettingPassword][failure] || false, }; }; const mapDispatchToProps = (dispatch) => { return { onCloseDialog: () => dispatch(navigateTo(routes.root)), requestResetPassword: (username) => dispatch(resetPasswordThunk({username})), }; }; export default connect( mapStateToProps, mapDispatchToProps )(injectIntl(ResetPassword));
demo08/src/components/Topics/Topics.js
lxlneo/reactdemo
import React from 'react'; import { Spin } from 'antd'; import styles from './Topics.css'; import ListItem from './ListItem'; function Topics({ data }) { const topics = data; return ( <div className={styles.normal}> <div className={styles.list}> { topics.map((v, k) => ( <ListItem value={v} key={k} /> )) } </div> <div className={styles.spinner}> <Spin type="large" /> </div> </div> ); } export default Topics;
sms_sponsorship/webapp/src/components/ChildDescription.js
maxime-beck/compassion-modules
import React from 'react'; import Typography from '@material-ui/core/Typography'; export default class extends React.Component { getDescriptionJson = () => { let div = document.createElement('div'); div.innerHTML = this.props.appContext.state.child.description; let table = div.querySelector('table'); function s(selector) { let elements = table.querySelectorAll(selector); switch(elements.length) { case 0: return false; case 1: return elements[0].innerHTML; default: let result = []; for (let i = 0; i < elements.length; i++) { result.push(elements[i].innerHTML); } return result.join(", "); } } function labelValue(parentClass, childClass) { let result = { label: s(parentClass + ' .desc_label' + childClass), value: s(parentClass + ' .desc_value' + childClass), }; return (result.label === false && result.value === false) ? false:result; } function labelValues(parentClass) { let result = { label: s(parentClass + ' ' + parentClass.replace('.', '#') + '_intro'), value: s(parentClass + ' ' + parentClass.replace('.', '#') + '_list li'), }; return (result.label === false && result.value === false) ? false:result; } return { program_type: s('.program_type'), birthday_estimate: s('.birthday_estimate'), live_with: s('#live_with'), family: { // father_alive: labelValue('.father', '.is_alive'), father_job: labelValue('.father_job', '.job'), // mother_alive: labelValue('.mother', '.is_alive'), mother_job: labelValue('.mother_job', '.job'), brothers: labelValue('', '.brothers'), sisters: labelValue('', '.sisters'), }, school: { school_attending: s('#school_attending'), school_performance: labelValue('', '.school_performance'), school_subject: labelValue('', '.school_subject'), vocational_training: labelValue('', '.vocational_training'), }, house_duties: labelValues('.house_duties'), church_activities: labelValues('.church_activities'), hobbies: labelValues('.hobbies'), handicap: labelValues('.handicap'), }; }; render() { let description_json = this.getDescriptionJson(); return ( <div style={{marginTop: '8px', marginLeft: '8px'}}> {Object.keys(description_json).map(item => <ChildDescriptionItem key={item} label={item} value={description_json[item]}/>)} </div> ) } } class ChildDescriptionItem extends React.Component { render() { const {value} = this.props; if (!value) { return ""; } if (typeof value === 'object') { let keys = Object.keys(value); if (keys.length === 2 && value['label'] !== 'undefined') { return <Typography variant="caption" gutterBottom>{value.label + " " + value.value}</Typography>; } return ( <div> {keys.map(item => <ChildDescriptionItem key={item} label={item} value={value[item]}/>)} </div> ) } return <Typography variant="caption" gutterBottom>{value}</Typography>; } }
packages/veritone-react-common/src/components/DataPicker/HeaderBar/story.js
veritone/veritone-sdk
import React from 'react'; import { storiesOf } from '@storybook/react'; import { text } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; import HeaderBar from './'; storiesOf('DataPicker', module) .add('HeaderBar: Basic', () => ( <HeaderBar pathList={[ { name: 'Parent', id: '1' }, { name: 'Child', id: '2' } ]} viewType={text('viewType', 'list')} onUpload={action('onUpload')} onSort={action('onSort')} onSearch={action('onSearch')} onCrumbClick={action('onCrumbClick')} onBack={action('onBack')} onClear={action('onClear')} onToggleView={action('onToggleView')} currentPickerType={text('currentPickerType', 'folder')} /> ))
app/index.js
JCombee/wallet
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
src/pages/NewSensor/NewSensorStepTwo.js
sussol/mobile
/* eslint-disable react/forbid-prop-types */ import React from 'react'; import { View, StyleSheet } from 'react-native'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { TabContainer } from './TabContainer'; import { BreachConfigRow } from './BreachConfigRow'; import { Paper, FlexRow, PageButton, Spacer } from '../../widgets'; import { AfterInteractions } from '../../widgets/AfterInteractions'; import { SUSSOL_ORANGE, WHITE } from '../../globalStyles'; import { buttonStrings, vaccineStrings } from '../../localization'; import { TemperatureBreachConfigActions, WizardActions } from '../../actions'; import { goBack } from '../../navigation/actions'; // eslint-disable-next-line max-len import { selectNewConfigsByType, selectNewConfigThresholds, } from '../../selectors/Entities/temperatureBreachConfig'; import { MILLISECONDS } from '../../utilities/constants'; export const NewSensorStepTwoComponent = ({ nextTab, previousTab, exit, hotConsecutiveConfig, coldCumulativeConfig, coldConsecutiveConfig, hotCumulativeConfig, updateDuration, updateTemperature, coldConsecutiveThreshold, hotConsecutiveThreshold, hotCumulativeThreshold, coldCumulativeThreshold, }) => ( <TabContainer> <Paper height={420} headerText={vaccineStrings.new_sensor_step_two_title}> <AfterInteractions placeholder={null}> <BreachConfigRow threshold={hotConsecutiveThreshold} type="HOT_CONSECUTIVE" {...hotConsecutiveConfig} updateDuration={updateDuration} updateTemperature={updateTemperature} containerStyle={localStyles.paperContentRow} /> <BreachConfigRow threshold={coldConsecutiveThreshold} type="COLD_CONSECUTIVE" {...coldConsecutiveConfig} updateDuration={updateDuration} updateTemperature={updateTemperature} containerStyle={localStyles.paperContentRow} /> <BreachConfigRow threshold={hotCumulativeThreshold} type="HOT_CUMULATIVE" {...hotCumulativeConfig} updateDuration={updateDuration} updateTemperature={updateTemperature} containerStyle={localStyles.paperContentRow} /> <BreachConfigRow threshold={coldCumulativeThreshold} type="COLD_CUMULATIVE" {...coldCumulativeConfig} updateDuration={updateDuration} updateTemperature={updateTemperature} containerStyle={localStyles.paperContentRow} /> </AfterInteractions> </Paper> <FlexRow flex={1} justifyContent="flex-end" alignItems="flex-end"> <View style={{ marginRight: 'auto' }}> <PageButton text={buttonStrings.back} onPress={previousTab} /> </View> <PageButton text={buttonStrings.cancel} onPress={exit} /> <Spacer space={20} /> <PageButton text={buttonStrings.next} style={{ backgroundColor: SUSSOL_ORANGE }} textStyle={{ color: WHITE }} onPress={nextTab} /> </FlexRow> </TabContainer> ); const localStyles = StyleSheet.create({ paperContentRow: { padding: 8, }, }); const stateToProps = state => { const { HOT_CONSECUTIVE: hotConsecutiveConfig, COLD_CONSECUTIVE: coldConsecutiveConfig, HOT_CUMULATIVE: hotCumulativeConfig, COLD_CUMULATIVE: coldCumulativeConfig, } = selectNewConfigsByType(state); const { coldConsecutiveThreshold, hotConsecutiveThreshold, hotCumulativeThreshold, coldCumulativeThreshold, } = selectNewConfigThresholds(state); return { hotConsecutiveConfig, coldCumulativeConfig, coldConsecutiveConfig, hotCumulativeConfig, coldConsecutiveThreshold, hotConsecutiveThreshold, hotCumulativeThreshold, coldCumulativeThreshold, }; }; const dispatchToProps = dispatch => { const nextTab = () => dispatch(WizardActions.nextTab()); const previousTab = () => dispatch(WizardActions.previousTab()); const exit = () => dispatch(goBack()); const updateDuration = (type, value) => dispatch( TemperatureBreachConfigActions.updateNewConfig( type, 'duration', value * MILLISECONDS.ONE_MINUTE ) ); const updateTemperature = (type, value) => { const field = type.includes('HOT') ? 'minimumTemperature' : 'maximumTemperature'; dispatch(TemperatureBreachConfigActions.updateNewConfig(type, field, value)); }; return { nextTab, previousTab, exit, updateDuration, updateTemperature }; }; NewSensorStepTwoComponent.defaultProps = { hotConsecutiveConfig: {}, coldCumulativeConfig: {}, coldConsecutiveConfig: {}, hotCumulativeConfig: {}, }; NewSensorStepTwoComponent.propTypes = { nextTab: PropTypes.func.isRequired, previousTab: PropTypes.func.isRequired, exit: PropTypes.func.isRequired, hotConsecutiveConfig: PropTypes.object, coldCumulativeConfig: PropTypes.object, coldConsecutiveConfig: PropTypes.object, hotCumulativeConfig: PropTypes.object, updateDuration: PropTypes.func.isRequired, updateTemperature: PropTypes.func.isRequired, coldConsecutiveThreshold: PropTypes.number.isRequired, hotConsecutiveThreshold: PropTypes.number.isRequired, hotCumulativeThreshold: PropTypes.number.isRequired, coldCumulativeThreshold: PropTypes.number.isRequired, }; export const NewSensorStepTwo = connect(stateToProps, dispatchToProps)(NewSensorStepTwoComponent);
frontend/app/js/components/board/settings.js
serverboards/serverboards
import React from 'react' import i18n from 'app/utils/i18n' import Modal from 'app/components/modal' import HoldButton from 'app/components/holdbutton' import {map_get} from 'app/utils' import ExtractorSelect from 'app/containers/board/extractorselect' class Settings extends React.Component{ constructor(props){ super(props) const {dashboard} = props this.state = { name: dashboard.name, config: dashboard.config, } } componentDidMount(){ $(this.refs.theme).dropdown({ onChange: (val) => this.setConfig("theme", val) }) } handleBoardUpdate(){ console.log("Save state:", this.state) const {name, config} = this.state const {uuid, order} = this.props.dashboard this.props.onBoardUpdate({uuid, name, config, order}) this.props.onClose() } handleBoardRemove(){ this.props.onBoardRemove() this.props.onClose() } setConfig(key, value){ const config = {...this.state.config, [key]: value} console.log("Update config", config) this.setState({config}) } render(){ const {onBoardRemove, dashboard} = this.props return ( <Modal> <div className="ui top serverboards secondary menu"> <h3 className="ui header">{i18n("{name} dashboard settings", {name: dashboard.name})}</h3> <div className="right menu"> <HoldButton className="item" onHoldClick={this.handleBoardRemove.bind(this)}> {i18n("Remove dashboard")} </HoldButton> </div> </div> <div className="ui text container with padding"> <div className="ui form"> <div className="ui field"> <label>{i18n("Dashboard name")}</label> <input type="text" defaultValue={dashboard.name} onChange={(ev) => this.setState({name: ev.target.value})}/> </div> <div className="ui field"> <label>{i18n("Style theme")}</label> <div className="ui selection dropdown" ref="theme"> <input type="hidden" name="theme" onChange={(ev) => this.setConfig("theme", ev.target.value)}/> <i className="dropdown icon"/> <div className="default text">{map_get(this.state, ["config", "theme"], "Light")}</div> <div className="menu"> <div className="item" data-value="light">Light</div> <div className="item" data-value="dark">Dark</div> </div> </div> </div> <ExtractorSelect extractors={map_get(this.state, ["config", "extractors"])} onSetExtractors={(extractors) => this.setConfig("extractors", extractors)} /> <div className="ui field"> <button className="ui teal button" onClick={this.handleBoardUpdate.bind(this)}> {i18n("Accept changes")} </button> </div> </div> </div> </Modal> ) } } export default Settings
yycomponent/popconfirm/Popconfirm.js
77ircloud/yycomponent
import React from 'react'; import { Popconfirm as _Popconfirm } from 'antd'; class Popconfirm extends React.Component{ constructor(props){ super(props); } render(){ return (<_Popconfirm {...this.props}/>); } } export default Popconfirm
packages/containers/src/TreeView/TreeView.stories.js
Talend/ui
import React from 'react'; import TreeView from '.'; export default { title: 'TreeView', }; export const Default = () => ( <TreeView id="my-treeview" collection="with.data" nameAttr="label" onToggleActionCreator="object:view" onSelectActionCreator="object:view" noHeader /> );
app/javascript/mastodon/features/favourites/index.js
Arukas/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavourites } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll-4'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]), }); @connect(mapStateToProps) export default class Favourites extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchFavourites(this.props.params.statusId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(nextProps.params.statusId)); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='favourites'> <div className='scrollable'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } }
example/examples/CustomTributeExample.js
BolsteDev/react-tribute
import React, { Component } from 'react'; import TextArea from 'react-textarea-autosize'; import options from './options'; import Tribute from '../../src/Tribute'; export default class CustomTributeExample extends Component { render() { return ( <div className="row"> <div className="large-8 columns"> <div className="callout large"> <h3>Tribute on custom textareas:</h3> <Tribute options={options}> <TextArea maxRows={2} placeholder="Try to @mention someone…"></TextArea> </Tribute> <div className="callout"> <pre> { `import TextArea from 'react-textarea-autosize'; // ... <Tribute options={options}> <TextArea maxRows={2}></TextArea> </Tribute> ` } </pre> </div> </div> </div> </div> ); } }
src/memo.js
Monar/react-immutable-pure-component
import React from 'react'; import { check } from './check'; export function immutableMemo(Component, updateOnProps) { return React.memo(Component, (prev, next) => check(updateOnProps, prev, next, 'immutableMemo'), ); }
packages/docs/components/Examples/alignment/SimpleAlignmentEditor/index.js
draft-js-plugins/draft-js-plugins
import React, { Component } from 'react'; import { convertFromRaw, DefaultDraftBlockRenderMap, EditorState, } from 'draft-js'; import Immutable from 'immutable'; import Editor, { composeDecorators } from '@draft-js-plugins/editor'; import createAlignmentPlugin from '@draft-js-plugins/alignment'; import createFocusPlugin from '@draft-js-plugins/focus'; import createColorBlockPlugin from './colorBlockPlugin'; import editorStyles from './editorStyles.module.css'; const focusPlugin = createFocusPlugin(); const alignmentPlugin = createAlignmentPlugin(); const { AlignmentTool } = alignmentPlugin; const decorator = composeDecorators( alignmentPlugin.decorator, focusPlugin.decorator ); const colorBlockPlugin = createColorBlockPlugin({ decorator }); const plugins = [focusPlugin, alignmentPlugin, colorBlockPlugin]; /* eslint-disable */ const initialState = { entityMap: { 0: { type: 'colorBlock', mutability: 'IMMUTABLE', data: {}, }, }, blocks: [ { key: '9gm3s', text: 'This is a simple example. Focus the block by clicking on it and change alignment via the toolbar.', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'ov7r', text: ' ', type: 'atomic', depth: 0, inlineStyleRanges: [], entityRanges: [ { offset: 0, length: 1, key: 0, }, ], data: {}, }, { key: 'e23a8', text: 'More text here to demonstrate how inline left/right alignment works …', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }; /* eslint-enable */ function BlockWrapper({ children }) { return <div className={editorStyles.wrapper}>{children}</div>; } const blockRenderMap = Immutable.Map({ atomic: { element: 'figure', wrapper: <BlockWrapper />, }, }); const extendedBlockRenderMap = DefaultDraftBlockRenderMap.merge(blockRenderMap); export default class SimpleAlignmentEditor extends Component { state = { editorState: EditorState.createWithContent(convertFromRaw(initialState)), }; onChange = (editorState) => { this.setState({ editorState, }); }; focus = () => { this.editor.focus(); }; render() { return ( <div> <div className={editorStyles.editor} onClick={this.focus}> <Editor editorState={this.state.editorState} onChange={this.onChange} plugins={plugins} ref={(element) => { this.editor = element; }} blockRenderMap={extendedBlockRenderMap} /> <AlignmentTool /> </div> </div> ); } }
src/app/core/atoms/icon/icons/calender.js
blowsys/reservo
import React from 'react'; const Calender = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><path d="M7,6 L7,5.0093689 C7,4.45190985 7.44386482,4 8,4 C8.55228475,4 9,4.44335318 9,5.0093689 L9,6 L15,6 L15,5.0093689 C15,4.45190985 15.4438648,4 16,4 C16.5522847,4 17,4.44335318 17,5.0093689 L17,6 L19,6 L19,18 L5,18 L5,6 L7,6 Z M7,16 L17,16 L17,10 L7,10 L7,16 Z"/><path d="M11,12.0093689 C11,11.4519098 11.4438648,11 12,11 C12.5522847,11 13,11.4433532 13,12.0093689 L13,13.9906311 C13,14.5480902 12.5561352,15 12,15 C11.4477153,15 11,14.5566468 11,13.9906311 L11,12.0093689 Z"/></g></g></svg>; export default Calender;
app/viewControllers/Auth/SendPasswordResetPage.js
Evyy/cffs-ui
'use strict'; import React from 'react'; import {Link} from 'react-router'; import classnames from "classnames"; import AuthPage from './AuthPage'; import SendResetForm from '../../forms/SendResetForm'; class SendPasswordResetPage extends React.Component { constructor (props) { super(props); } render () { let authClass = classnames('send-password-reset-page'); return ( <AuthPage className={authClass} title="Password Reset"> <SendResetForm/> <div className="auth-links"> <Link to="/login">&lt;- Back to login </Link> </div> </AuthPage> ); } } export default SendPasswordResetPage;
src/routes/adminModify/index.js
oct16/Blog-FE
import React from 'react'; import Layout from 'components/Layout'; const title = 'Admin Modify'; const isAdmin = false; export default { path: '/admin/modify/:id', async action({ fetch, params }) { const AdminModify = await require.ensure([], require => require('./AdminModify').default, 'AdminModify') const resp = await fetch('/api/v1/post/' + params.id) if (resp.status !== 200) { return { redirect: '/login' } } const post = await resp.json() return { title, chunk: 'AdminModify', component: <Layout><AdminModify title={title} post={post} params={params}/></Layout>, }; }, };
src/index.js
tsaarikivi/goose
import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import { Provider } from 'react-redux' import { Router, hashHistory } from 'react-router' import routes from './routes' import store from './store' // create redux store and apply middleware let reduxStore = createStore(store, applyMiddleware(thunk)) // initialize firebase import firebase from 'firebase' /*STAGE CONFIG*/ const fbconfig = { apiKey: "AIzaSyBuxqd56LzPir8sWbYC06uk2jf-Yn_4R-M", authDomain: "goose-platform.firebaseapp.com", databaseURL: "https://goose-platform.firebaseio.com", storageBucket: "goose-platform.appspot.com", messagingSenderId: "1086707450695" } /*PRODUCTION CONFIG const fbconfig = { }*/ firebase.initializeApp(fbconfig) // set firebase auth eventlistener // this function could be outside in a separate component firebase.auth().onAuthStateChanged(function (user) { if (user) { console.log("logged in as:", user) // we could send a reduxStore.dispatch() here // or call an action to fetch user data from db // this should at least lead to a state change } else { console.log("logged out") } }) // render applications in place of #app-entry in index.html ReactDOM.render( <Provider store={reduxStore}> <Router history={hashHistory} routes={routes} /> </Provider>, document.getElementById('app-entry') )
vendor/assets/components/react-autosuggest/examples/src/Badges/Badges.js
UMNLibraries/ikidowinan
require('./Badges.less'); import React, { Component } from 'react'; export default class Badges extends Component { render() { return ( <div className="badges"> <a href="//codeship.com/projects/67868" target="_blank"> <img src="//img.shields.io/codeship/41810250-aa07-0132-fbf4-4e62e8945e03/master.svg" alt="build status" /> </a> <a href="//npmjs.org/package/react-autosuggest" target="_blank"> <img src="//img.shields.io/npm/v/react-autosuggest.svg" alt="npm version" /> </a> <a href="//npmjs.org/package/react-autosuggest" target="_blank"> <img src="//img.shields.io/npm/dm/react-autosuggest.svg" alt="npm downloads" /> </a> </div> ); } }
src/components/Toggle/Toggle.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import { settings } from 'carbon-components'; import setupGetInstanceId from '../../tools/setupGetInstanceId'; import { keys, match } from '../../tools/key'; const { prefix } = settings; const getInstanceId = setupGetInstanceId(); class Toggle extends React.Component { static propTypes = { /** * Specify a custom className to apply to the form-item node */ className: PropTypes.string, /** * Specify whether the toggle should be on by default */ defaultToggled: PropTypes.bool, /** * Provide an optional hook that is called when the control is toggled */ onToggle: PropTypes.func, /** * Provide an id that unique represents the underlying <input> */ id: PropTypes.string.isRequired, /** * Specify whether the control is toggled */ toggled: PropTypes.bool, /** * Specify the label for the "off" position */ labelA: PropTypes.string.isRequired, /** * Specify the label for the "on" position */ labelB: PropTypes.string.isRequired, }; static defaultProps = { defaultToggled: false, label: '', labelA: 'Off', labelB: 'On', onToggle: () => {}, }; render() { const { className, defaultToggled, toggled, onChange, onToggle, id = (this.inputId = this.inputId || `__carbon-toggle_${getInstanceId()}`), labelText, labelA, labelB, ...other } = this.props; let input; const wrapperClasses = classNames({ [`${prefix}--form-item`]: true, [className]: className, }); const checkedProps = {}; if (typeof toggled !== 'undefined') { checkedProps.checked = toggled; } else { checkedProps.defaultChecked = defaultToggled; } const labelTextId = !labelText ? undefined : `${id}-label`; return ( <> {labelText && ( <div id={labelTextId} className={`${prefix}--label`}> {labelText} </div> )} <div className={wrapperClasses}> <input {...other} {...checkedProps} type="checkbox" id={id} className={`${prefix}--toggle`} aria-labelledby={labelTextId} onChange={evt => { onChange && onChange(evt); onToggle(input.checked, id, evt); }} ref={el => { input = el; }} onKeyUp={evt => { if (match(evt, keys.ENTER)) { input.checked = !input.checked; onChange(evt); onToggle(input.checked, id, evt); } }} /> <label className={`${prefix}--toggle__label`} htmlFor={id}> <span className={`${prefix}--toggle__text--left`} aria-hidden="true"> {labelA} </span> <span className={`${prefix}--toggle__appearance`} /> <span className={`${prefix}--toggle__text--right`} aria-hidden="true"> {labelB} </span> </label> </div> </> ); } } export default Toggle;
src/svg-icons/action/description.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDescription = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/> </SvgIcon> ); ActionDescription = pure(ActionDescription); ActionDescription.displayName = 'ActionDescription'; ActionDescription.muiName = 'SvgIcon'; export default ActionDescription;
code/L5/Component-Lifecycle/hello-world.js
santhoshthepro/reactjs
import React from 'react'; import LifecycleComponent from './lifecycle-component'; class HelloWorld extends React.Component{ render(){ return (<div> <h1>Welcome to Webpack!</h1> <LifecycleComponent/> </div> ); } } export default HelloWorld
demo/textfield/textfield.js
koorchik/react-mdl
import React from 'react'; import Textfield from '../../src/Textfield'; function linkToState(target, property) { return value => { target.setState({ [property]: value }); }; } class Demo extends React.Component { constructor(props) { super(props); this.state = { textfield1: '', textfield2: '', textfield3: '', textfield4: '', textfield5: '', textfield6: '' }; } render() { return ( <form action='#'> <p>Simple textfield</p> <Textfield value={this.state.textfield1} onChange={linkToState(this, 'textfield1')} label="Text..." style={{width: '200px'}} /> <p>Numeric textfield</p> <Textfield value={this.state.textfield2} onChange={linkToState(this, 'textfield2')} pattern="-?[0-9]*(\.[0-9]+)?" error="Input is not a number!" label="Number..." style={{width: '200px'}} /> <p>Textfield with floating label</p> <Textfield value={this.state.textfield3} onChange={linkToState(this, 'textfield3')} label="Text..." floatingLabel={true} style={{width: '200px'}} /> <p>Numeric Textfield with floating label</p> <Textfield value={this.state.textfield4} onChange={linkToState(this, 'textfield4')} pattern="-?[0-9]*(\.[0-9]+)?" error="Input is not a number!" label="Number..." floatingLabel={true} /> <p>Floating Multiline Textfield</p> <Textfield value={this.state.textfield5} onChange={linkToState(this, 'textfield5')} label="Text lines..." rows={3} style={{width: '200px'}} /> <p>Expandable Textfield</p> <Textfield value={this.state.textfield6} onChange={linkToState(this, 'textfield6')} label="Expandable Input" expandable={true} expandableIcon="search" /> </form> ); } } React.render(<Demo />, document.getElementById('app'));
src/Parser/Druid/Restoration/Modules/Items/EssenceOfInfusion.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing'; import ItemHealingDone from 'Main/ItemHealingDone'; const HEALING_BREAKPOINT = 0.6; const HEALING_INCREASE = 0.6; class EssenceOfInfusion extends Analyzer { static dependencies = { combatants: Combatants, }; healing = 0; on_initialized() { this.active = this.combatants.selected.hasFeet(ITEMS.ESSENCE_OF_INFUSION.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.TRANQUILITY_HEAL.id) { const healthBeforeHeal = event.hitPoints - event.amount; const healthBreakpoint = event.maxHitPoints * HEALING_BREAKPOINT; if (healthBeforeHeal <= healthBreakpoint) { this.healing += calculateEffectiveHealing(event, HEALING_INCREASE); } } } item() { return { item: ITEMS.ESSENCE_OF_INFUSION, result: <ItemHealingDone amount={this.healing} />, }; } } export default EssenceOfInfusion;
src/course/curriculum.js
TJCU-Dev/tjcu-site-frontend
import React from 'react'; import {grey200, grey400, grey800, grey900, grey600, red900} from 'material-ui/styles/colors'; import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import IconButton from 'material-ui/IconButton'; export default class Curriculum extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div> <Table selectable={false} > <TableHeader enableSelectAll={false} displaySelectAll={false}> <TableRow > <TableHeaderColumn>周一</TableHeaderColumn> <TableHeaderColumn>周二</TableHeaderColumn> <TableHeaderColumn>周三</TableHeaderColumn> <TableHeaderColumn>周四</TableHeaderColumn> <TableHeaderColumn>周五</TableHeaderColumn> <TableHeaderColumn>周六</TableHeaderColumn> <TableHeaderColumn>周日</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={true} > <TableRow > <TableRowColumn>油画人物</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn>综合绘画</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> <TableRow > <TableRowColumn>油画人物</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn>综合绘画</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn>当代水墨研习</TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> <TableRow > <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> <TableRow > <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> <TableRow > <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> <TableRow > <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn></TableRowColumn> <TableRowColumn>油画静物</TableRowColumn> </TableRow> </TableBody> </Table> </div> ) } }
frontend/components/confirm-view.js
meandavejustice/min-vid
import React from 'react'; import sendToAddon from '../client-lib/send-to-addon'; import sendMetricsEvent from '../client-lib/send-metrics-event'; export default class ConfirmView extends React.Component { cancel(ev) { ev.preventDefault(); ev.stopPropagation(); sendMetricsEvent('confirm_view', 'cancel'); sendToAddon({action: 'confirm', choice: 'cancel'}); } confirmVideo(ev) { ev.preventDefault(); ev.stopPropagation(); sendToAddon(Object.assign(this.props.confirmContent, { action: 'confirm', choice: 'video', playerMethod: this.props.confirmContent.action, moveIndexZero: Boolean(window.AppData.currentTime) })); } confirmPlaylist(ev) { ev.preventDefault(); ev.stopPropagation(); sendToAddon(Object.assign(this.props.confirmContent, { action: 'confirm', choice: 'playlist', playerMethod: this.props.confirmContent.action, moveIndexZero: Boolean(window.AppData.currentTime) })); } render() { const preMsg = (this.props.confirmContent.action === 'play') ? this.props.strings.playConfirmMsg : this.props.strings.addConfirmMsg; return ( <div className='confirm'> <p className='confirm-message'>{this.props.strings.confirmMsg}</p> <br/> <br/> <a className='btn' onClick={this.confirmVideo.bind(this)}> <span className='truncated'>{`${preMsg} ${this.props.confirmContent.videoTitle}`}</span></a> <p className='or'>--------</p> <a className='btn' onClick={this.confirmPlaylist.bind(this)}> <span className='truncated'>{`${preMsg} ${this.props.confirmContent.playlistTitle}`}</span></a> <a className="cancel" onClick={this.cancel.bind(this)}>Do nothing</a> </div> ); } }
app/index.js
kentlan/sound-cloud-redux-app
import React from 'react' import {render} from 'react-dom' import App from './containers/app' import {Provider} from 'react-redux' import store from './store' import './style/scss/style.scss' const root = ( <Provider store={store}> <App/> </Provider> ) render(root, document.getElementById('app'))
node_modules/react-router/es/IndexRedirect.js
aalpgiray/react-hot-boilerplate-ts
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import Redirect from './Redirect'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ var IndexRedirect = React.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRedirect;
src/components/ConnectedArray.js
mzvonar/modular-redux-form
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import getIn from '@mzvonar/getin'; import isEvent from './../utils/isEvent'; import deepEqual from 'react-fast-compare'; function deleteChildren(object, children) { let deleted = {}; for(let i = 0, length = children.length; i < length; i += 1) { const key = children[i]; if(Object.prototype.hasOwnProperty.call(object, key)) { deleted[key] = object[key]; delete object[key]; } } return deleted; } function cleanComponentProps(props) { const componentProps = Object.assign({}, props); const input = componentProps.input; const value = componentProps.value; deleteChildren(componentProps, [ 'component', 'input', 'value', '_mrf', ]); const items = []; if(input.name && value) { for(let i = 0, length = value.length; i < length; i += 1) { items.push(`${input.name}[${i}]`); } } componentProps.items = items; return componentProps; } function getValue(event) { if(isEvent(event)) { return event.target.value; } else { return event; } } function generateErrorMessages(errors, errorMessages) { const messages = []; if(errors && errors.length > 0 && errorMessages) { for(let i = 0, length = errors.length; i < length; i += 1) { if(errorMessages[errors[i]]) { messages.push(errorMessages[errors[i]]); } } } return messages; } const ignoreForUpdate = [ '_mrf' ]; class ConnectedArray extends React.Component { static get propTypes() { return { component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired, name: PropTypes.string.isRequired } } constructor(props, context) { super(props, context); } UNSAFE_componentWillMount() { this.props._mrf.registerInput(this.props.name, { isArray: true, required: this.props.required, validate: this.props.validate, value: (this.props.type === 'hidden' && this.props.value) ? this.props.value : undefined }, this.props.initialValue, this.props.initialErrors); } componentWillUnmount() { this.props._mrf.removeInput(this.props.name); } shouldComponentUpdate(nextProps, nextState) { const nextPropsKeys = Object.keys(nextProps); const thisPropsKeys = Object.keys(this.props); if(nextPropsKeys.length !== thisPropsKeys.length) { return true; } for(let i = 0, length = nextPropsKeys.length; i < length; i += 1) { const key = nextPropsKeys[i]; if(!~ignoreForUpdate.indexOf(key) && !deepEqual(this.props[key], nextProps[key])) { return true } } return false; } // UNSAFE_componentWillReceiveProps(nextProps) { // if(this.props.type === 'hidden' && nextProps.value !== this.props.value) { // this.onChange(nextProps.value); // } // } onChange(e) { this.props._mrf.inputChange(this.props.name, getValue(e)); if(this.props.onChange) { this.props.onChange(e); } } onBlur(e) { this.props._mrf.inputBlur(this.props.name); if(this.props._mrf.asyncValidate) { this.props._mrf.asyncValidate(this.props.name, getValue(e), true, false); } if(this.props.onBlur) { this.props.onBlur(e); } } render() { const formSubmitted = this.props.formSubmitted; let componentProps = cleanComponentProps(this.props); // Object.assign(componentProps.input, { // onChange: this.onChange, // onBlur: this.onBlur, // }); if(Object.prototype.toString.call(this.props.component) !== '[object Function]') { // return React.createElement(this.props.component, Object.assign(componentProps.input, { // type: this.props.type, // className: this.props.className // })); throw new Error('Component must be a fucntion or class'); } else { const bindArray = actionCreator => actionCreator.bind(null, this.props.name); return React.createElement(this.props.component, Object.assign(componentProps, { meta: { pristine: this.props.input.pristine, dirty: this.props.input.dirty, touched: formSubmitted === true ? true : this.props.input.touched, valid: this.props.input.valid, errors: this.props.input.errors, errorMessages: generateErrorMessages(this.props.input.errors, this.props.errors), initialErrors: this.props.input.initialErrors, asyncValidation: this.props.input.asyncValidation, asyncErrors: this.props.input.asyncErrors, formSubmitted: formSubmitted }, actions: { push: bindArray(this.props._mrf.arrayPush), pop: bindArray(this.props._mrf.arrayPop), shift: bindArray(this.props._mrf.arrayShift), unshift: bindArray(this.props._mrf.arrayUnshift), insert: bindArray(this.props._mrf.arrayInsert), remove: bindArray(this.props._mrf.arrayRemove), removeAll: bindArray(this.props._mrf.arrayRemoveAll), } })); } } } function mapStateToProps(state, ownProps) { const formState = ownProps._mrf.getFormState(state); return { input: getIn(formState, ['inputs', ownProps.name]) || {}, value: getIn(formState, ['values', ...ownProps.name.split('.')]), initialValue: getIn(formState, ['initialValues', ...ownProps.name.split('.')]), initialErrors: getIn(formState, ['initialInputErrors', ownProps.name]), formSubmitted: getIn(formState, 'submitted', false) } } const mapDispatchToProps = {}; export default connect(mapStateToProps, mapDispatchToProps)(ConnectedArray);
src/app/js/Header.js
skratchdot/colorify
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { Row, Col, Nav } from 'react-bootstrap'; class Header extends Component { isLinkActive = (name) => { return this.props.active === name ? 'active' : ''; }; render() { const { active } = this.props; const HeaderLink = ({ to, pageName }) => { const className = active === pageName ? 'active' : ''; return ( <li className={className}> <Link to={to}>{pageName}</Link> </li> ); }; return ( <div> <Row className="header"> <Col md={6}> <Link to="/colorify"> <h1 className="title"> Colorify &nbsp; <small>a collection of color tools</small> </h1> </Link> </Col> <Col md={6}> <Nav bsStyle="pills"> <HeaderLink to="/colorify" pageName="Home" /> <HeaderLink to="/colorify/about" pageName="About" /> <HeaderLink to="/colorify/stats" pageName="Stats" /> <HeaderLink to="/colorify/mixer" pageName="Mixer" /> <HeaderLink to="/colorify/math" pageName="Math" /> </Nav> </Col> </Row> <Row> <Col md={12}> <div className="color-stripe" /> </Col> </Row> </div> ); } } export default Header;
examples/fiber/debugger/src/Fibers.js
claudiopro/react
import React from 'react'; import { Motion, spring } from 'react-motion'; import dagre from 'dagre'; import prettyFormat from 'pretty-format'; import reactElement from 'pretty-format/plugins/ReactElement'; function getFiberColor(fibers, id) { if (fibers.currentIDs.indexOf(id) > -1) { return 'lightgreen'; } if (id === fibers.workInProgressID) { return 'yellow'; } return 'lightyellow'; } function Graph(props) { var g = new dagre.graphlib.Graph(); g.setGraph({ width: 1000, height: 1000, nodesep: 50, edgesep: 150, ranksep: 150, marginx: 100, marginy: 100, }); var edgeLabels = {}; React.Children.forEach(props.children, function(child) { if (!child) { return; } if (child.type.isVertex) { g.setNode(child.key, { label: child, width: child.props.width, height: child.props.height }); } else if (child.type.isEdge) { const relationshipKey = child.props.source + ':' + child.props.target; if (!edgeLabels[relationshipKey]) { edgeLabels[relationshipKey] = []; } edgeLabels[relationshipKey].push(child); } }); Object.keys(edgeLabels).forEach(key => { const children = edgeLabels[key]; const child = children[0]; g.setEdge(child.props.source, child.props.target, { label: child, allChildren: children.map(c => c.props.children), weight: child.props.weight }); }); dagre.layout(g); var activeNode = g.nodes().map(v => g.node(v)).find(node => node.label.props.isActive ); const [winX, winY] = [window.innerWidth / 2, window.innerHeight / 2] var focusDx = activeNode ? (winX - activeNode.x) : 0; var focusDy = activeNode ? (winY - activeNode.y) : 0; var nodes = g.nodes().map(v => { var node = g.node(v); return ( <Motion style={{ x: props.isDragging ? node.x + focusDx : spring(node.x + focusDx), y: props.isDragging ? node.y + focusDy : spring(node.y + focusDy) }} key={node.label.key}> {interpolatingStyle => React.cloneElement(node.label, { x: interpolatingStyle.x + props.dx, y: interpolatingStyle.y + props.dy, vanillaX: node.x, vanillaY: node.y, }) } </Motion> ); }); var edges = g.edges().map(e => { var edge = g.edge(e); let idx = 0; return ( <Motion style={edge.points.reduce((bag, point) => { bag[idx + ':x'] = props.isDragging ? point.x + focusDx : spring(point.x + focusDx); bag[idx + ':y'] = props.isDragging ? point.y + focusDy : spring(point.y + focusDy); idx++; return bag; }, {})} key={edge.label.key}> {interpolatedStyle => { let points = []; Object.keys(interpolatedStyle).forEach(key => { const [idx, prop] = key.split(':'); if (!points[idx]) { points[idx] = { x: props.dx, y: props.dy }; } points[idx][prop] += interpolatedStyle[key]; }); return React.cloneElement(edge.label, { points, id: edge.label.key, children: edge.allChildren.join(', ') }); }} </Motion> ); }); return ( <div style={{ position: 'relative', height: '100%' }}> {edges} {nodes} </div> ); } function Vertex(props) { if (Number.isNaN(props.x) || Number.isNaN(props.y)) { return null; } return ( <div style={{ position: 'absolute', border: '1px solid black', left: (props.x-(props.width/2)), top: (props.y-(props.height/2)), width: props.width, height: props.height, overflow: 'hidden', padding: '4px', wordWrap: 'break-word' }}> {props.children} </div> ); } Vertex.isVertex = true; const strokes = { alt: 'blue', child: 'green', sibling: 'darkgreen', return: 'red', fx: 'purple', progressedChild: 'cyan', progressedDel: 'brown' }; function Edge(props) { var points = props.points; var path = "M" + points[0].x + " " + points[0].y + " "; if (!points[0].x || !points[0].y) { return null; } for (var i = 1; i < points.length; i++) { path += "L" + points[i].x + " " + points[i].y + " "; if (!points[i].x || !points[i].y) { return null; } } var lineID = props.id; return ( <svg width="100%" height="100%" style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }}> <defs> <path d={path} id={lineID} /> <marker id="markerCircle" markerWidth="8" markerHeight="8" refX="5" refY="5"> <circle cx="5" cy="5" r="3" style={{stroke: 'none', fill:'black'}}/> </marker> <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto"> <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: 'black'}} /> </marker> </defs> <use xlinkHref={`#${lineID}`} fill="none" stroke={strokes[props.kind]} style={{ markerStart: 'url(#markerCircle)', markerEnd: 'url(#markerArrow)' }} /> <text> <textPath xlinkHref={`#${lineID}`}> {'     '}{props.children} </textPath> </text> </svg> ); } Edge.isEdge = true; function formatPriority(priority) { switch (priority) { case 1: return 'synchronous'; case 2: return 'task'; case 3: return 'animation'; case 4: return 'hi-pri work'; case 5: return 'lo-pri work'; case 6: return 'offscreen work'; default: throw new Error('Unknown priority.'); } } export default function Fibers({ fibers, show, ...rest }) { const items = Object.keys(fibers.descriptions).map(id => fibers.descriptions[id] ); const isDragging = rest.className.indexOf('dragging') > -1; const [_, sdx, sdy] = rest.style.transform.match(/translate\((\-?\d+)px,(\-?\d+)px\)/) || []; const dx = Number(sdx); const dy = Number(sdy); return ( <div {...rest} style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, ...rest.style, transform: null }}> <Graph className="graph" dx={dx} dy={dy} isDragging={isDragging} > {items.map(fiber => [ <Vertex key={fiber.id} width={200} height={100} isActive={fiber.id === fibers.workInProgressID}> <div style={{ width: '100%', height: '100%', backgroundColor: getFiberColor(fibers, fiber.id) }} title={prettyFormat(fiber, { plugins: [reactElement ]})}> <small>{fiber.tag} #{fiber.id}</small> <br /> {fiber.type} <br /> {fibers.currentIDs.indexOf(fiber.id) === -1 ? <small> {fiber.pendingWorkPriority !== 0 && [ <span style={{ fontWeight: fiber.pendingWorkPriority <= fiber.progressedPriority ? 'bold' : 'normal' }} key="span"> Needs: {formatPriority(fiber.pendingWorkPriority)} </span>, <br key="br" /> ]} {fiber.progressedPriority !== 0 && [ `Finished: ${formatPriority(fiber.progressedPriority)}`, <br key="br" /> ]} {fiber.memoizedProps !== null && fiber.pendingProps !== null && [ fiber.memoizedProps === fiber.pendingProps ? 'Can reuse memoized.' : 'Cannot reuse memoized.', <br /> ]} </small> : <small> Committed </small> } </div> </Vertex>, fiber.child && show.child && <Edge source={fiber.id} target={fiber.child} kind="child" weight={1000} key={`${fiber.id}-${fiber.child}-child`}> child </Edge>, fiber.progressedChild && show.progressedChild && <Edge source={fiber.id} target={fiber.progressedChild} kind="progressedChild" weight={1000} key={`${fiber.id}-${fiber.progressedChild}-pChild`}> pChild </Edge>, fiber.sibling && show.sibling && <Edge source={fiber.id} target={fiber.sibling} kind="sibling" weight={2000} key={`${fiber.id}-${fiber.sibling}-sibling`}> sibling </Edge>, fiber.return && show.return && <Edge source={fiber.id} target={fiber.return} kind="return" weight={1000} key={`${fiber.id}-${fiber.return}-return`}> return </Edge>, fiber.nextEffect && show.fx && <Edge source={fiber.id} target={fiber.nextEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.nextEffect}-nextEffect`}> nextFx </Edge>, fiber.firstEffect && show.fx && <Edge source={fiber.id} target={fiber.firstEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.firstEffect}-firstEffect`}> firstFx </Edge>, fiber.lastEffect && show.fx && <Edge source={fiber.id} target={fiber.lastEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.lastEffect}-lastEffect`}> lastFx </Edge>, fiber.progressedFirstDeletion && show.progressedDel && <Edge source={fiber.id} target={fiber.progressedFirstDeletion} kind="progressedDel" weight={100} key={`${fiber.id}-${fiber.progressedFirstDeletion}-pFD`}> pFDel </Edge>, fiber.progressedLastDeletion && show.progressedDel && <Edge source={fiber.id} target={fiber.progressedLastDeletion} kind="progressedDel" weight={100} key={`${fiber.id}-${fiber.progressedLastDeletion}-pLD`}> pLDel </Edge>, fiber.alternate && show.alt && <Edge source={fiber.id} target={fiber.alternate} kind="alt" weight={10} key={`${fiber.id}-${fiber.alternate}-alt`}> alt </Edge>, ])} </Graph> </div> ); }
app/containers/CatKitDemo/BulkInput.js
mhoffman/CatAppBrowser
import _ from 'lodash'; import React from 'react'; import PropTypes, { instanceOf } from 'prop-types'; import { Link } from 'react-router'; import { withCookies, Cookies } from 'react-cookie'; import { compose } from 'recompose'; import { MenuItem } from 'material-ui/Menu'; import Select from 'material-ui/Select'; import Button from 'material-ui/Button'; import Grid from 'material-ui/Grid'; import Paper from 'material-ui/Paper'; import FaCube from 'react-icons/lib/fa/cube'; import { withStyles } from 'material-ui/styles'; import Input, { InputLabel } from 'material-ui/Input'; import { LinearProgress } from 'material-ui/Progress'; import { FormControl, FormHelperText } from 'material-ui/Form'; import { MdClear } from 'react-icons/lib/md'; import axios from 'axios'; import { apiRoot } from 'utils/constants'; import { outputFormats } from 'components/GeometryCanvasWithOptions'; import { styles } from './styles'; const backendRoot = `${apiRoot}/apps/catKitDemo`; const url = `${backendRoot}/convert_atoms/`; const bulkUrl = `${backendRoot}/generate_bulk_cif`; const wyckoffUrl = `${apiRoot}/apps/bulkEnumerator/get_wyckoff_from_cif`; let initialState = { structure: 'fcc', latticeConstant: 3.93, coverage: 1, u: 1, elements: ['Pt', 'Pt', 'Pt', 'Pt'], uploadError: '', loading: false, inputFormat: 'cif', }; const structureData = { fcc: { nspecies: 2, label: 'FCC', }, bcc: { nspecies: 2, label: 'BCC', }, sc: { nspecies: 2, label: 'SC', }, hcp: { nspecies: 4, label: 'HCP', extraParams: { covera: { label: 'c/a', }, }, }, diamond: { nspecies: 2, label: 'Diamond', }, zincblende: { nspecies: 2, label: 'Zinc Blende', }, rocksalt: { nspecies: 2, label: 'Rock Salt', }, cesiumchloride: { nspecies: 2, label: 'Cesium Chloride', }, fluorite: { nspecies: 2, label: 'Fluorite', }, wurtzite: { nspecies: 4, label: 'Wurtzite', extraParams: { u: { label: 'u', }, }, }, }; class BulkInput extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); let latticeConstant; if (this.props.routeParams.latticeConstant) { if (!isNaN(parseFloat(this.props.routeParams.latticeConstant))) { latticeConstant = parseFloat(this.props.routeParams.latticeConstant); } else { latticeConstant = 3.99; } } else { latticeConstant = 3.99; } const structure = this.props.routeParams.lattice || 'fcc'; let elements; if (this.props.routeParams.composition) { elements = this.props.routeParams.composition.match(/[A-Z][a-z]?/g); } else { elements = _.get(this.props, 'bulkParams.elements', undefined); if (typeof elements === 'string') { elements = JSON.parse(elements); } else if (typeof elements === 'undefined') { elements = ['Pt']; } } while (elements.length < structureData[structure].nspecies) { elements.unshift(elements[0]); } initialState = _.extend(initialState, { structure, elements, latticeConstant, }); // Sync initial state with cookie if (this.props.cookies.get('preferredFormat') === undefined) { this.props.cookies.set( 'preferredFormat', initialState.inputFormat, ); } else { initialState.inputFormat = this.props.cookies.get('preferredFormat'); } this.state = initialState; this.generateBulk = this.generateBulk.bind(this); this.handleChange = this.handleChange.bind(this); this.handleFileDrop = this.handleFileDrop.bind(this); this.setState({ loading: true, }); setTimeout(() => { this.generateBulk(); this.setState({ loading: false, }); }, 1000, ); } generateBulk = () => { const params = { params: { bulkParams: { lattice_constant: this.state.latticeConstant, structure: this.state.structure, elements: this.state.elements.slice(0, structureData[this.state.structure].nspecies), u: this.state.u, covera: this.state.covera, wyckoff: this.props.bulkParams.wyckoff, format: this.state.inputFormat, }, } }; this.props.clearSlabCifs(); /* this.props.saveBulkParams(params.params.bulkParams);*/ if (!this.props.customBulkInput) { axios.get(bulkUrl, params).then((response) => { this.props.receiveBulkCif(response.data.cifdata); if (typeof response.data.lattice_constants !== 'undefined') { this.setState({ latticeConstant: response.data.lattice_constants.toFixed(3), }); } const wyckoffParams = { cif: response.data.cifdata, }; params.params.bulkParams.lattice_constant = response.data.lattice_constant; params.params.bulkParams.input = response.data.input; params.params.bulkParams.cif = response.data.cifdata; axios.get(wyckoffUrl, { params: wyckoffParams }).then((wyckoffResponse) => { params.params.bulkParams.wyckoff = wyckoffResponse.data; this.props.saveBulkParams(params.params.bulkParams); }); }); } } handleChange(name) { return (event) => { if (name.match(/^element/) === null) { this.setState({ [name]: event.target.value, }); } else { const n = name.split(/(?=[0-9])/)[1]; const elements = this.state.elements; elements[n] = event.target.value; this.setState({ elements, }); } if (name === 'structure') { const elements = this.state.elements; while (this.state.elements.length < structureData[event.target.value].nspecies) { elements.unshift(elements[0]); } this.setState({ elements, }); } }; } handleFileDrop(files) { const formData = new FormData(); formData.append('file', files[0]); formData.append('outFormat', 'cif'); this.props.dropBulkInput(files[0]); axios.post(url, formData, { headers: { 'content-type': 'multipart/form-data' } }).then((response) => { if (!_.isEmpty(response.data.image)) { this.props.receiveBulkCif(response.data.image); } if (!_.isEmpty(response.data.error)) { this.setState({ uploadError: response.data.error, }); } else { this.setState({ uploadError: '', }); } } ); } render() { return ( <Paper className={this.props.classes.paper}> <div>Note: use <Link to="/bulkGenerator">Wyckoff Bulk Constructor</Link> for generating arbitrary bulk structures or <Link to="/prototypeSearch">Prototype Search</Link> to search among existing ones.</div> <Grid container justify="space-between" direction="row" > <Grid item> <h2>Setup Bulk Structure</h2> </Grid> <Grid item> <Button disabled={_.isEmpty(this.props.bulkCif)} onClick={() => { this.props.clearBulkCif(); this.props.forgetCustomBulk(); }} className={this.props.classes.button} ><MdClear /> {'\u00A0\u00A0'}Clear </Button> <Button raised onClick={this.generateBulk} color="primary" className={this.props.classes.button}><FaCube />{'\u00A0\u00A0'} Generate </Button> </Grid> </Grid> {this.props.customBulkInput ? null : <form> <FormControl className={this.props.classes.formControl} > <InputLabel htmlFor="structure-simple">Lattice like</InputLabel> <Select value={this.state.structure} onKeyDown={((event) => { if (event.nativeEvent.keyCode === 13) { this.generateBulk(); } })} onChange={(event) => { this.handleChange('structure')(event); this.generateBulk(); }} > {Object.keys(structureData).map((structure) => ( <MenuItem key={`item_${structure}`} value={structure}>{_.get(structureData, [structure]).label}</MenuItem> ))} </Select> </FormControl> { Object.keys(_.get(structureData, [this.state.structure, 'extraParams'], {})).map((extraParam) => ( <FormControl className={this.props.classes.formControl} key={`extraParam_${extraParam}`}> <InputLabel htmlFor={extraParam}>{structureData[this.state.structure].extraParams[extraParam].label}</InputLabel> <Input autoFocus id={extraParam} value={_.get(this.state, [extraParam])} onChange={this.handleChange(extraParam)} onKeyDown={((event) => { if (event.nativeEvent.keyCode === 13) { this.generateBulk(); } })} /> <FormHelperText></FormHelperText> </FormControl> )) } {_.range(_.get(structureData, [this.state.structure, 'nspecies'])).map((n) => ( <FormControl className={this.props.classes.formControl} key={`fc_${n}`} > <InputLabel htmlFor={`element${n}-helper`}>{`Element ${n}`}</InputLabel> <Input autoFocus id={`element${n}-helper`} value={_.get(this.state, ['elements', n])} onChange={this.handleChange(`element${n}`)} onKeyDown={((event) => { if (event.nativeEvent.keyCode === 13) { this.generateBulk(); } })} /> <FormHelperText></FormHelperText> </FormControl> )) } <FormControl className={this.props.classes.formControl} > <InputLabel htmlFor="lattice-constant-helper" >Lattice Constant</InputLabel> <Input id="lattice-constant-helper" disabled value={this.state.latticeConstant} onChange={this.handleChange('latticeConstant')} onKeyDown={((event) => { if (event.nativeEvent.keyCode === 13) { this.generateBulk(); } })} /> <FormHelperText>{'Default based on Vegard\'s law'}</FormHelperText> </FormControl> <FormControl className={this.props.classes.formContro}> <InputLabel htmlFor="input-format-helper" >Input Format</InputLabel> <Select id="input-format-helper" value={this.state.inputFormat} onChange={(event) => { this.setState({ inputFormat: event.target.value, }); this.props.cookies.set( 'preferredFormat', event.target.value, ); }} > {outputFormats.map((format, i) => ( <MenuItem key={`format_${i}`} value={format}>{format}</MenuItem> ))} </Select> </FormControl> </form> } {this.state.loading === true ? <LinearProgress className={this.props.classes.progress} /> : null } </Paper> ); } } BulkInput.propTypes = { bulkCif: PropTypes.string, bulkParams: PropTypes.object, classes: PropTypes.object.isRequired, clearBulkCif: PropTypes.func, clearSlabCifs: PropTypes.func, cookies: instanceOf(Cookies), customBulkInput: PropTypes.bool, dropBulkInput: PropTypes.func, forgetCustomBulk: PropTypes.func, latticeConstant: PropTypes.number, receiveBulkCif: PropTypes.func.isRequired, routeParams: PropTypes.object, saveBulkParams: PropTypes.func, }; export default compose( withStyles(styles, { withTheme: true }), withCookies, )(BulkInput);
src/components/BookmarksList.js
dan-f/mark
import React from 'react' import NewBookmark from './NewBookmark' import Bookmark from './Bookmark' import ListGroup from './ListGroup' import ListGroupItem from './ListGroupItem' import BookmarkEditor from '../containers/BookmarkEditor' export default function BookmarksList ({ bookmarks, handleCancelEditing, handleClickEdit, handleSelectTag }) { return ( <section aria-label='Bookmark list' aria-live='polite'> <div className='row'> <div className='col'> <ListGroup> <ListGroupItem> <NewBookmark /> </ListGroupItem> {bookmarks.map(bookmark => bookmark.get('isEditing') ? <ListGroupItem key={bookmark.getIn(['data', 'book:recalls', '@id'])}> <BookmarkEditor key={bookmark.getIn(['data', 'book:recalls', '@id'])} bookmark={bookmark} handleCancel={handleCancelEditing(bookmark)} /> </ListGroupItem> : <ListGroupItem key={bookmark.getIn(['data', 'book:recalls', '@id'])}> <Bookmark title={bookmark.getIn(['data', 'dc:title', '@value'])} url={bookmark.getIn(['data', 'book:recalls', '@id'])} tags={bookmark.getIn(['data', 'book:hasTopic']).map(tag => tag.get('@value'))} comments={bookmark.getIn(['data', 'dc:description', '@value'])} onClickEdit={handleClickEdit(bookmark)} handleSelectTag={handleSelectTag} /> </ListGroupItem> )} </ListGroup> </div> </div> </section> ) }
src/components/HTMLEditor.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { upload } from '../lib/api'; import '../../node_modules/react-quill/dist/quill.snow.css'; /* * Simple editor component that takes placeholder text as a prop */ class HTMLEditor extends React.Component { static propTypes = { placeholder: PropTypes.string, defaultValue: PropTypes.string, className: PropTypes.string, onChange: PropTypes.func, }; constructor(props) { super(props); this.state = { editorHtml: props.defaultValue, theme: 'snow' }; this.handleChange = this.handleChange.bind(this); this.saveToServer = this.saveToServer.bind(this); this.insertToEditor = this.insertToEditor.bind(this); if (typeof window !== 'undefined') { this.ReactQuill = require('react-quill'); } /* * Quill modules to attach to editor * See https://quilljs.com/docs/modules/ for complete options */ this.modules = { toolbar: { container: [ [{ header: '1' }, { header: '2' }], [{ size: [] }], ['bold', 'italic', 'underline', 'blockquote'], [{ list: 'ordered' }, { list: 'bullet' }], ['link', 'image', 'video'], ], handlers: { image: () => { this.selectLocalImage(); }, }, }, clipboard: { // toggle to add extra line breaks when pasting HTML: matchVisual: false, }, }; /* * Quill editor formats * See https://quilljs.com/docs/formats/ */ this.formats = [ 'header', 'font', 'size', 'bold', 'italic', 'underline', 'strike', 'blockquote', 'list', 'bullet', 'indent', 'link', 'image', 'video', ]; } componentDidUpdate(oldProps) { if (this.props.value !== oldProps.value) { this.setState({ editorHtml: this.props.value }); } } handleChange(html) { this.setState({ editorHtml: html }); this.props.onChange(html); } selectLocalImage() { const input = document.createElement('input'); input.setAttribute('type', 'file'); input.click(); // Listen upload local image and save to server input.onchange = () => { const file = input.files[0]; // file type is only image. if (/^image\//.test(file.type)) { this.saveToServer(file); } else { console.warn('You can only upload images.'); } }; } /** * Step2. save to server * * @param {File} file */ saveToServer(file) { upload(file) .then(fileUrl => { return this.insertToEditor(fileUrl); }) .catch(e => { console.error('Error uploading image', e); }); } /** * Step3. insert image url to rich editor. * * @param {string} url */ insertToEditor(url) { const editor = this.reactQuillRef.getEditor(); // push image url to rich editor. const range = editor.getSelection(); editor.insertEmbed(range.index, 'image', url); } render() { if (!this.ReactQuill) { return <div />; } return ( <div className={classNames('HTMLEditor', this.props.className)}> <style jsx> {` .HTMLEditor :global(.quill) { height: auto; } .HTMLEditor :global(.ql-container) { min-height: 20rem; max-height: 35rem; overflow-y: auto; } .HTMLEditor.small :global(.quill) { height: auto; min-height: 20rem; } .HTMLEditor.small :global(.ql-container) { height: 15rem; } `} </style> <this.ReactQuill ref={el => (this.reactQuillRef = el)} theme="snow" onChange={this.handleChange} value={this.state.editorHtml || ''} defaultValue={this.props.defaultValue || ''} modules={this.modules} formats={this.formats} bounds={'.app'} placeholder={this.props.placeholder} /> </div> ); } } // // quill editor add image handler // HTMLEditor.getModule('toolbar').addHandler('image', () => { // selectLocalImage(); // }); export default HTMLEditor;
src/svg-icons/action/assignment-late.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentLate = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-6 15h-2v-2h2v2zm0-4h-2V8h2v6zm-1-9c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/> </SvgIcon> ); ActionAssignmentLate = pure(ActionAssignmentLate); ActionAssignmentLate.displayName = 'ActionAssignmentLate'; ActionAssignmentLate.muiName = 'SvgIcon'; export default ActionAssignmentLate;
desenvolvimento-plataformas-moveis/pocs/camera/App.js
mfklauberg/projetosacademicosfurb
import React from 'react'; import { StyleSheet, Text, View, Button, Alert, Image, CameraRoll } from 'react-native'; import { Permissions, ImagePicker } from 'expo' export default class App extends React.Component { render() { return ( <View style={styles.container}> <View style={styles.header}> <Text style={styles.header_text}>POC 3 - Camera</Text> </View> <View> <CustomImagePicker /> </View> </View> ); } } class CustomImagePicker extends React.Component { constructor(props) { super(props); this.state = { hasPermission: undefined }; } askCameraPermission() { const checkPromise = Permissions.getAsync(Permissions.CAMERA); checkPromise.then(checkResponse => { const { status } = checkResponse; if (status === 'granted') { this.setState({ hasPermission: true }); return; } const permissionPromise = Permissions.askAsync(Permissions.CAMERA); permissionPromise.then(response => { const { status } = response; this.setState({ hasPermission: status === 'granted' }); }); }); } pickImage() { const galleryPromise = ImagePicker.launchImageLibraryAsync({ allowsEditing: true }); galleryPromise.then(response => { const { cancelled, uri, width, height } = response; if (cancelled) { this.setState({ hasImage: false }); return; } this.setState({ hasImage: true, image: { uri, width, height } }) }); } takeImage() { const cameraPromise = ImagePicker.launchCameraAsync({ allowsEditing: true }); cameraPromise.then(response => { const { cancelled, uri, width, height } = response; if (cancelled) { this.setState({ hasImage: false }); return; } this.setState({ hasImage: true, image: { uri, width, height } }); CameraRoll.saveToCameraRoll(this.state.image.uri); }); } render() { const permissionButton = () => !this.state.hasPermission ? <Button title="Ask permission to use camera" onPress={() => this.askCameraPermission()} /> : <View></View> const permissionText = this.state.hasPermission === true ? 'Permission granted!' : this.state.hasPermission === false ? `The app doesn't have permission to access the camera!` : ''; const picker = (text, fn) => this.state.hasPermission ? <Button title={text} onPress={() => fn.apply(this)} /> : <View></View>; const statusText = this.state.hasPermission ? this.state.hasImage ? '' : 'No image selected' : ''; const image = () => this.state.hasImage ? <Image source={this.state.image} style={{ height: this.state.image.height > 250 ? 250 : this.state.image.height, width: this.state.image.width > 250 ? 250 : this.state.image.width }} /> : <Image /> return ( <View> {permissionButton()} {picker('take a picture', this.takeImage)} {picker('choose one from the gallery', this.pickImage)} <Text>{statusText}</Text> {image()} </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: '#fff', alignItems: 'center' }, header: { margin: 20 }, header_text: { fontSize: 24 }, input: { height: 100 } });
examples/huge-apps/app.js
hgezim/react-router
import React from 'react'; import { Router } from 'react-router'; import stubbedCourses from './stubs/COURSES'; var rootRoute = { component: 'div', childRoutes: [{ path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile'), ] }] }; React.render( <Router routes={rootRoute} />, document.getElementById('example') ); // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like // // import { Route } from 'react-router' // import App from './components/App'; // import Course from './routes/Course/components/Course'; // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar'; // import Announcements from './routes/Course/routes/Announcements/components/Announcements'; // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement'; // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar'; // import Assignments from './routes/Course/routes/Assignments/components/Assignments'; // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment'; // import CourseGrades from './routes/Course/routes/Grades/components/Grades'; // import Calendar from './routes/Calendar/components/Calendar'; // import Grades from './routes/Grades/components/Grades'; // import Messages from './routes/Messages/components/Messages'; // React.render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // );
examples/components/Content.js
neilff/react-d3-examples
import React from 'react'; const Content = ({ children, isVisible }) => { const visibleClass = isVisible ? 'block' : 'hide'; return ( <div className={ `mt3 p1 ${ visibleClass }` } style={{ ...styles.base, styles }}> { children } </div> ); }; const styles = { base: {}, }; export default Content;
src/routes.js
civic-tech-lab/commonplace-frontend
// @flow import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { App, Main } from './components'; // React router v4 - https://reacttraining.com/react-router/ const appRoutes = ( <Switch> <Route path="/" exact component={Main} /> <Route path="/about" exact component={() => <div>Example About Page route</div>} /> <Route component={() => <div>Placeholder 404 page</div>} /> </Switch> ); const baseRoute = ( <Route path="/" render={props => <App {...props}>{appRoutes}</App>} /> ); export default baseRoute;
src/ModalHeader.js
egauci/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import tbsUtils, { bsClass } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; class ModalHeader extends React.Component { render() { let { 'aria-label': label, ...props } = this.props; let onHide = createChainedFunction(this.context.$bs_onModalHide, this.props.onHide); return ( <div {...props} className={classNames(this.props.className, tbsUtils.prefix(this.props, 'header'))} > { this.props.closeButton && <button type="button" className="close" aria-label={label} onClick={onHide}> <span aria-hidden="true"> &times; </span> </button> } { this.props.children } </div> ); } } ModalHeader.propTypes = { /** * The 'aria-label' attribute provides an accessible label for the close button. * It is used for Assistive Technology when the label text is not readable. */ 'aria-label': React.PropTypes.string, bsClass: 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.contextTypes = { '$bs_onModalHide': React.PropTypes.func }; ModalHeader.defaultProps = { 'aria-label': 'Close', closeButton: false }; export default bsClass('modal', ModalHeader);
app/react-native/app/screens/StatsScreen.js
sping/abcd-epic-fussball
import React, { Component } from 'react'; import { StyleSheet, Text, Image, View, ScrollView } from 'react-native'; import { Card } from 'react-native-elements' import Constants from '../config/constants'; import Colors from '../config/colors'; import Player from '../models/player'; const GET_CURRENT_PLAYER_STATS_URI = Constants.BASE_URL + 'current_user/stats'; class StatsScreen extends Component { constructor(props) { super(props); this.state = { playerStats: {}, pic: { uri: "http://simpleicon.com/wp-content/uploads/football.png" } }; } componentDidMount() { this.fetchData(); } render() { return ( <ScrollView style={styles.container}> <View> <View style={styles.imageContainer}> <Image source={this.state.pic} style={styles.theimage} /> </View> <Card style={styles.contentview}> <View style={styles.item}> <Text style={styles.text}>Ranking</Text> <Text style={styles.text}>{this.state.playerStats.ranking}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Win ratio</Text> <Text style={styles.text}>{this.state.playerStats.gameRatio}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Wins</Text> <Text style={styles.text}>{this.state.playerStats.gamesWon}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Fails</Text> <Text style={styles.text}>{this.state.playerStats.gamesLost}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Goals for</Text> <Text style={styles.text}>{this.state.playerStats.goalsFor}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Goals against</Text> <Text style={styles.text}>{this.state.playerStats.goalsAgainst}</Text> </View> <View style={styles.item}> <Text style={styles.text}>Goals diff</Text> <Text style={styles.text}>{this.state.playerStats.goalsDiff}</Text> </View> </Card> </View> </ScrollView> ); } fetchData() { var headers = new Headers(); headers.append("Authorization", "Token token=" + Constants.API_TOKEN); fetch(GET_CURRENT_PLAYER_STATS_URI, { headers: headers, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); var player = new Player(responseData.user); this.setState({ playerStats: responseData.stat, player: player, pic: { uri: player.getPlayerImageUrl() } }); }) .done(); } } export default StatsScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.grey6 }, imageContainer: { marginTop: 100, marginBottom: 40, alignItems: 'center', justifyContent: 'center' }, theimage: { flex: 0, width: 80, height: 80, borderRadius: 40 }, contentview: { flexDirection: 'column', flex: 1, width: '100%', paddingLeft: '10%', paddingRight: '10%' }, item: { flexDirection: 'row', marginBottom: 20 }, text: { flex: 1, fontSize: 20 } });
004 - Logicless Components with Reselect/src/components/posts_list.js
StephenGrider/RallyCodingWeekly
import _ from 'lodash'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from 'actions'; class PostsList extends Component { componentWillMount() { this.props.fetchPosts(); } handlePostSelect({ id }, event) { const { selectPost, deselectPost } = this.props; event.target.checked ? selectPost(id) : deselectPost(id); } renderPost(post) { console.log(_.contains(this.props.selectedPostIds, post.id)) return ( <li className="list-group-item" key={post.id}> <input checked={_.contains(this.props.selectedPostIds, post.id)} type="checkbox" onChange={this.handlePostSelect.bind(this, post)} /> {post.title} </li> ); } render() { return ( <ul className="list-group"> {_.map(this.props.posts, this.renderPost.bind(this))} </ul> ); } } export default connect(({posts, selectedPostIds}) => ({posts, selectedPostIds}) , actions)(PostsList)
examples/todos/src/containers/AddTodo.js
ioof-holdings/redux-dynamic-reducer
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
lib/routes.js
conveyal/scenario-editor
// @flow /** * React Router container to be rendered by woonerf/mount. * @author mattwigway */ import React from 'react' import {IndexRoute, Router, Route} from 'react-router' import {load as loadProject} from './actions/project' import {load as loadRegion} from './actions/region' import Admin from './modules/admin' import * as auth0 from './utils/auth0' import Bundles from './components/bundles' import CreateBundle from './containers/create-bundle' import CreateProject from './containers/create-project' import CreateRegion from './containers/create-region' import EditBundle from './containers/edit-bundle' import EditRegion from './containers/edit-region' import EditProject from './containers/edit-project' import NotFound from './components/404.js' import ImportModifications from './containers/import-modifications' import ImportShapefile from './containers/import-shapefile' import ModificationEditor from './containers/modification-editor' import Modifications from './containers/modifications' import SelectRegion from './containers/select-region' import SelectProject from './containers/select-project' import SinglePointAnalysis from './containers/single-point-analysis' import OpportunityDatasets from './modules/opportunity-datasets' import Report from './containers/report' import RegionalResultsList from './containers/regional-results-list' import Regional from './containers/regional-analysis-results' import * as select from './selectors' type Props = { store: any } // initialize the application export default class Routes extends React.Component { // Default redirect to base url (in case a user goes directly to `/login`) _redirectTo = '/' constructor (props: Props) { super(props) // allow the store to be accessible from the command line if (window) window.store = props.store window.select = {} Object.keys(select).forEach(key => { window.select[key] = () => select[key](props.store.getState()) }) } _checkAuthentication = (nextState: any) => { const user = this.props.store.getState().user if (auth0.authIsRequired && !user) { this._redirectTo = `${nextState.location.pathname}${nextState.location.search}` this.props.history.push('/login') } } _login = () => { // Login with Auth0 and get the user data. auth0.login((user) => { // set in the store this.props.store.dispatch({ type: 'set user', payload: user }) // redirect back this.props.history.push(this._redirectTo) }) } _loadRegion = (nextState: any, _: any, callback: Function) => { this.props.store.dispatch(loadRegion(nextState.params.regionId, callback)) } _loadProject = (nextState: any, _: any, callback: Function) => { this.props.store.dispatch(loadProject(nextState.params.projectId, callback)) } _logout = () => { this.props.store.dispatch({ type: 'set user', payload: null }) auth0.logout() } _redirectHome = () => { setTimeout(() => { this.props.history.push('/') }, 3000) } render () { // Mount the routes return ( <Router history={this.props.history}> <Route path='/login' onEnter={this._login} /> <Route path='/logout' onEnter={this._logout} /> <Route path='/' onEnter={this._checkAuthentication}> <IndexRoute component={SelectRegion} /> <Route path='regions' component={SelectRegion} /> <Route path='reports/:regionId/projects/:projectId/variants/:variantId' component={Report} /> <Route path='admin' component={Admin.components.MainDashboard} /> <Route path='admin/jobs' component={Admin.components.JobDashboard} /> <Route path='admin/workers' component={Admin.components.WorkerDashboard} /> <Route path='regions/create' component={CreateRegion} /> <Route onEnter={this._loadRegion} path='regions/:regionId' > <IndexRoute component={SelectProject} /> <Route path='analysis' component={SinglePointAnalysis} /> <Route path='regional' component={RegionalResultsList} /> <Route path='regional/:regionalAnalysisId' component={Regional} /> <Route path='projects' component={SelectProject} /> <Route path='bundles' component={Bundles}> <IndexRoute component={EditBundle} /> <Route path='create' component={CreateBundle} /> <Route path=':bundleId' component={EditBundle} /> </Route> <Route component={OpportunityDatasets.components.Heading} path='opportunities' > <IndexRoute component={OpportunityDatasets.components.List} /> <Route path='upload' component={OpportunityDatasets.components.Upload} /> </Route> <Route path='edit' component={EditRegion} /> <Route path='projects' component={SelectProject} /> <Route path='create-project' component={CreateProject} /> <Route onEnter={this._loadProject} path='projects/:projectId' > <IndexRoute component={Modifications} /> <Route path='edit' component={EditProject} /> <Route path='import-modifications' component={ImportModifications} /> <Route path='import-shapefile' component={ImportShapefile} /> <Route path='modifications' component={Modifications} /> <Route path='modifications/:modificationId' component={ModificationEditor} /> </Route> </Route> </Route> <Route path='*' component={NotFound} onEnter={this._redirectHome} /> </Router> ) } }
react/app/Story.js
yogeshkhatri1989/hn
import React, { Component } from 'react'; import ReactFire from 'reactfire'; import { Route, Link } from 'react-router-dom'; import StoryComment from './StoryComment'; import UserProfile from './UserProfile'; class Story extends Component { constructor(props) { super(props); this.state = {}; } componentWillMount() { ReactFire.componentWillMount.call(this); const ref = this.props.firebaseRootRef.child(`/v0/item/${this.props.storyId}`); ReactFire.bindAsObject.call(this, ref, "story"); } prefetchStoryStuffs(story) { (story.kids || []).forEach(kid => { if (this.state[`storyComments${kid}`]) return; const ref = this.props.firebaseRootRef.child(`/v0/item/${kid}`); ReactFire.bindAsObject.call(this, ref, `storyComments${kid}`); }); } componentWillUpdate(nextProps, nextState) { if (!this.state.story) return; let currStory = this.state.story; let nextStory = nextState.story; let elems = []; if (nextStory.score != currStory.score) { elems.push([ this.refs.storyScore, nextStory.score > currStory.score ? "moveup" : "movedown" ]); } if (nextStory.descendants != currStory.descendants) { elems.push([ this.refs.storyDescendants, nextStory.descendants > currStory.descendants ? "moveup" : "movedown" ]); } elems.forEach(elem => elem[0].classList.add(elem[1])); setTimeout(function() { elems.forEach(elem => elem[0].classList.remove("moveup", "movedown")) }, 2500); } render() { let story = this.state.story; let storyCont = this.props.storyCont; if (story) { story.displayUrl = story.url ? new URL(story.url).host : ""; story.timeByAgo = getTimeByAgo(story.time); } return ( <div className="hn-story"> {story ? <div ref="storyCont" className="story-cont" onMouseEnter={this.prefetchStoryStuffs.bind(this, story)}> <div className="center-content"> {/* <span className="story-index">{this.props.storyIndex + 1}. </span> */} { story.url ? <a className="story-link" href={story.url} target="_blank">{story.title}</a> : <Link className="story-link" to={`/story/${storyCont}/${story.id}`}>{story.title}</Link> } <span className="url-cont"> ({story.displayUrl})</span> <div className="bottom-bar"> <span ref="storyScore" className="story-prop story-score">{story.score} Points</span> <span className="story-prop story-by"> <Link to={`/story/${storyCont}/user/${story.id}/${story.by}`} className="user-profile-link"> By {story.by} </Link> </span> <span className="story-prop story-time">{story.timeByAgo}</span> </div> </div> <Link to={`/story/${storyCont}/${story.id}`} className="right-side"> <span ref="storyDescendants">{story.descendants} Comments</span> </Link> <Route path={`/story/:storyType/${story.id}`} render={(props) => ( <StoryComment firebaseRootRef={this.props.firebaseRootRef} {...props} story={story} /> )} /> <Route path={`/story/:storyType/user/${story.id}/:userId`} render={(props) => ( <UserProfile firebaseRootRef={this.props.firebaseRootRef} {...props} /> )} /> </div> : "Loading..."} </div> ); } } function getTimeByAgo(time){ var timeByAgo = (Date.now()/1000) - time; var timeNames = [ {name: "Second", value: timeByAgo }, {name: "Minute", value: timeByAgo / (60) }, {name: "Hour", value: timeByAgo / (60 * 60)}, {name: "Day", value: timeByAgo / (24 * 60 * 60) }, {name: "Month", value: timeByAgo / (30 * 24 * 60 * 60) }, {name: "Year", value: timeByAgo / (365 * 24 * 60 * 60) } ]; var i; for (i = 0; i < timeNames.length; i++){ if (timeNames[i].value < 1) { i--; break; } } i = Math.min(i, timeNames.length - 1); timeByAgo = parseInt(timeNames[i].value); var name = timeByAgo == 1 ? timeNames[i].name : timeNames[i].name + "s"; return timeByAgo + " " + name.toLowerCase() + " ago" } export default Story;
src/svg-icons/action/book.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBook = (props) => ( <SvgIcon {...props}> <path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/> </SvgIcon> ); ActionBook = pure(ActionBook); ActionBook.displayName = 'ActionBook'; ActionBook.muiName = 'SvgIcon'; export default ActionBook;
js/components/weather.js
stage88/react-weather
/** * @flow */ 'use strict'; import StatusBar from 'StatusBar'; import React, { Component } from 'react'; import { StyleSheet, View, Animated, Image, Text, Dimensions } from 'react-native'; import { connect } from 'react-redux'; import Swiper from '../dependencies/swiper'; import Header from './header'; import Footer from './footer'; import Forecast from './forecast'; import Loading from './loading'; import type { WeatherModel } from '../models/view' const SCREEN_WIDTH = Dimensions.get('window').width; type Props = { dispatch: any; isLoading: bool; weather: Array<WeatherModel>; count: number; navigator: any; }; type State = { shift: Animated.Value; current: number; }; class Weather extends Component { props: Props; state: State; constructor(props: Props) { super(props); this.state = { shift: new Animated.Value(0), current: 0 }; (this: any).onScroll = this.onScroll.bind(this); (this: any).onSelectedIndexChange = this.onSelectedIndexChange.bind(this); } render() { if (this.props.isLoading === true) { return ( <Loading /> ); } var forecastItems = this.props.weather.map((item, index) => { return ( <Forecast key={`forecast-${index}`} forecast={item.forecast} /> ); }); var swiper = ( <Swiper showsPagination={false} loop={false} onScroll={this.onScroll} onSelectedIndexChange={this.onSelectedIndexChange} scrollEventThrottle={8}> { forecastItems } </Swiper> ); return ( <View style={styles.container}> <Header offset={this.state.shift} current={this.state.current}> { swiper } </Header> <Footer current={this.state.current} count={this.props.count} navigator={this.props.navigator} /> </View> ); } onSelectedIndexChange(index, offset) { this.setState({current: index}); } onScroll(e) { this.state.shift.setValue(e.nativeEvent.contentOffset.x); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F9F9F9' } }); function select(store: any, props: Props) { return { isLoading: store.weather.isLoading, weather: store.weather.data, count: store.weather.data.length, ...props }; } module.exports = connect(select)(Weather);
components/Header/index.js
YongYuH/Ludo
import React from 'react'; import styled from 'styled-components'; import Avatar from './Avatar'; import HeaderLeft from './HeaderLeft'; const HeaderWrapper = styled.div` align-items: center; background-color: #717070; display: flex; height: 40px; position: relative; `; const Header = () => ( <HeaderWrapper> <HeaderLeft /> <Avatar /> </HeaderWrapper> ); export default Header;
src/components/Spinner/index.js
trebor/tsomi
// @flow import React from 'react' import { type Element } from 'react' require('./main.css') type SpinnerProps = { className: string, } const Spinner = (props: SpinnerProps): Element<'div'> => React.createElement('div', { className: `spinner ${props.className}` }) export default Spinner
src/svg-icons/maps/restaurant-menu.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsRestaurantMenu = (props) => ( <SvgIcon {...props}> <path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z"/> </SvgIcon> ); MapsRestaurantMenu = pure(MapsRestaurantMenu); MapsRestaurantMenu.displayName = 'MapsRestaurantMenu'; MapsRestaurantMenu.muiName = 'SvgIcon'; export default MapsRestaurantMenu;
example/pages/page/index.js
woshisbb43/coinMessageWechat
import React from 'react'; import { Article, Page } from '../../../build/packages'; import srcArticle from '../article/pic_article.png'; const PageDemo = (props) => ( <Page transition={true} infiniteLoader={true} ptr={false}> <Article> <h1>Page Demo</h1> <section> <h2 className="title">H2 Title</h2> <section> <h3>H3 Heading</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute</p> <p> <img src={srcArticle} alt/> <img src={srcArticle} alt/> </p> </section> <section> <h3>H3 Heading</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> </section> </Article> </Page> ); export default PageDemo;
source/components/Application.react.js
elliotk/thinkreact-kleiman
// Custom component import React from 'react' var logs = require('../utilities/logsMixin.js') const Section = require('./Section.react.js') const Banner = require('./Banner.react.js') const Header = require('./Header.react.js') const Overview = require('./Overview.react.js') const Bullets = require('./Bullets.react.js') const Photos = require('./Photos.react.js') const Tweets = require('./Tweets.react.js') const Application = React.createClass({ name:"Application", //mixins:[logs], render:function(){ //object property: value return(<div> <Banner /> <Section><Header>Overview</Header><Overview /></Section> <Section><Header>Bullets</Header><Bullets /></Section> <Section><Header>Photos</Header><Photos /></Section> <Section><Header>Tweets</Header><Tweets /></Section> </div>); } }); module.exports = Application;
examples/counter-1/src/index.js
rerx/rerx
import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; import { select, run } from 'rerx/core'; import { Counter } from './Counter'; const mountNode = document.getElementById("root"); const component$ = select(components => components); // Mounting components are observable. component$.subscribe(components => { console.info(components); }); // Events are observable. select('#my-counter', 'incrementClick').subscribe(e => { console.log(e); }); // States are observable. select('#my-counter', 'count$').subscribe(count => { console.log(count); }); render(<Counter id="my-counter" /> , mountNode, run); // Try calling unmount() from the console. window.unmount = () => unmountComponentAtNode(mountNode);
src/svg-icons/navigation/close.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationClose = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); NavigationClose = pure(NavigationClose); NavigationClose.displayName = 'NavigationClose'; NavigationClose.muiName = 'SvgIcon'; export default NavigationClose;
src/screen/LogicAnalyser/LogicAnalyser.js
wavicles/fossasia-pslab-apps
import React, { Component } from 'react'; import { connect } from 'react-redux'; import debounce from 'lodash/debounce'; import GraphPanelLayout from '../../components/GraphPanelLayout'; import Graph from './components/Graph'; import ActionButtons from './components/ActionButtons'; import Settings from './components/Settings'; const electron = window.require('electron'); const { ipcRenderer } = electron; const loadBalancer = window.require('electron-load-balancer'); class LogicAnalyser extends Component { constructor(props) { super(props); this.state = { isReading: false, numberOfChannels: 1, channel1Map: 'ID1', channel2Map: 'ID2', trigger1Type: 1, trigger2Type: 1, trigger3Type: 1, trigger4Type: 1, timeMeasureChannel1: 'ID1', timeMeasureChannel2: 'ID2', timeMeasuretrigger1Type: 1, timeMeasuretrigger2Type: 1, timeMeasureWrite1: 1, timeMeasureWrite2: 2, timeout: 10, }; } componentDidMount() { ipcRenderer.on('CONNECTION_STATUS', (event, args) => { const { isConnected } = args; isConnected && this.getConfigFromDevice(); }); ipcRenderer.on('LA_CONFIG', (event, args) => { const { numberOfChannels, trigger1Type, trigger2Type, trigger3Type, trigger4Type, } = args; this.setState({ numberOfChannels, trigger1Type, trigger2Type, trigger3Type, trigger4Type, }); }); this.getConfigFromDevice(); } componentWillUnmount() { const { isReading } = this.state; isReading && loadBalancer.sendData(ipcRenderer, 'linker', { command: 'STOP_LA', }); ipcRenderer.removeAllListeners('LA_CONFIG'); } getConfigFromDevice = debounce(() => { const { isConnected } = this.props; isConnected && loadBalancer.sendData(ipcRenderer, 'linker', { command: 'GET_CONFIG_LA', }); }, 500); sendConfigToDevice = debounce(() => { const { isConnected } = this.props; const { numberOfChannels, trigger1Type, trigger2Type, trigger3Type, trigger4Type, } = this.state; isConnected && loadBalancer.sendData(ipcRenderer, 'linker', { command: 'SET_CONFIG_LA', numberOfChannels, trigger1Type, trigger2Type, trigger3Type, trigger4Type, }); }, 500); toggleRead = () => { const { isReading } = this.state; this.setState(prevState => ({ isReading: !prevState.isReading })); if (isReading) { loadBalancer.sendData(ipcRenderer, 'linker', { command: 'STOP_LA', }); } else { loadBalancer.sendData(ipcRenderer, 'linker', { command: 'START_LA', }); } }; changeNumberOfChannels = event => { this.setState( { numberOfChannels: event.target.value, }, () => { this.sendConfigToDevice(); }, ); }; changeChannelMap = channelName => event => { this.setState({ [channelName]: event.target.value, }); }; changeTriggerType = triggerNumber => event => { this.setState( { [triggerNumber]: event.target.value, }, () => { this.sendConfigToDevice(); }, ); }; changeTimeMeasureChannel = channelName => event => { this.setState({ [channelName]: event.target.value, }); }; changeTimeMeasureTriggerType = triggerNumber => event => { this.setState({ [triggerNumber]: event.target.value, }); }; changeTimeMeasureWrite = writeNumber => event => { this.setState({ [writeNumber]: event.target.value, }); }; changeTimeout = (event, value) => { this.setState({ timeout: value, }); }; render() { const { isReading, numberOfChannels, channel1Map, channel2Map, trigger1Type, trigger2Type, trigger3Type, trigger4Type, timeMeasureChannel1, timeMeasureChannel2, timeMeasuretrigger1Type, timeMeasuretrigger2Type, timeMeasureWrite1, timeMeasureWrite2, timeout, } = this.state; const { isConnected } = this.props; return ( <GraphPanelLayout settings={ <Settings numberOfChannels={numberOfChannels} channel1Map={channel1Map} channel2Map={channel2Map} trigger1Type={trigger1Type} trigger2Type={trigger2Type} trigger3Type={trigger3Type} trigger4Type={trigger4Type} timeMeasureChannel1={timeMeasureChannel1} timeMeasureChannel2={timeMeasureChannel2} timeMeasuretrigger1Type={timeMeasuretrigger1Type} timeMeasuretrigger2Type={timeMeasuretrigger2Type} timeMeasureWrite1={timeMeasureWrite1} timeMeasureWrite2={timeMeasureWrite2} timeout={timeout} changeNumberOfChannels={this.changeNumberOfChannels} changeChannelMap={this.changeChannelMap} changeTriggerType={this.changeTriggerType} changeTimeMeasureChannel={this.changeTimeMeasureChannel} changeTimeMeasureTriggerType={this.changeTimeMeasureTriggerType} changeTimeMeasureWrite={this.changeTimeMeasureWrite} changeTimeout={this.changeTimeout} /> } actionButtons={ <ActionButtons isConnected={isConnected} isReading={isReading} toggleRead={this.toggleRead} /> } graph={ <Graph isReading={isReading} numberOfChannels={numberOfChannels} toggleRead={this.toggleRead} /> } /> ); } } const mapStateToProps = state => ({ isConnected: state.app.device.isConnected, }); export default connect( mapStateToProps, null, )(LogicAnalyser);
src/renderer/app.js
marcus-sa/Venobo
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { AppContainer } from 'react-hot-loader' import { IntlProvider } from './components/react-multilingual' import config from '../config' export default function createApp(store, appState, translations) { const dest = document.querySelector('#content-wrapper') const render = () => { const Routes = require('./routes') ReactDOM.render( <AppContainer> <Provider store={store}> <IntlProvider translations={translations}> <Routes appState={appState} /> </IntlProvider> </Provider> </AppContainer>, dest ) } render() if (module.hot) { module.hot.accept('./routes', render) } if (config.IS.DEV) { const devToolsDest = document.createElement('div') window.document.body.insertBefore(devToolsDest, null) const { DevTools } = require('./components') ReactDOM.render( <Provider store={store} key="provider"> <DevTools /> </Provider>, devToolsDest ) } }
src/svg-icons/content/backspace.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentBackspace = (props) => ( <SvgIcon {...props}> <path d="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 12.59L17.59 17 14 13.41 10.41 17 9 15.59 12.59 12 9 8.41 10.41 7 14 10.59 17.59 7 19 8.41 15.41 12 19 15.59z"/> </SvgIcon> ); ContentBackspace = pure(ContentBackspace); ContentBackspace.displayName = 'ContentBackspace'; ContentBackspace.muiName = 'SvgIcon'; export default ContentBackspace;
app/Pages/SettlementViewNew/ReceiptAddress/AddressDetail.js
jd-daojia/DaojiaRN
/* @flow */ import React, { Component } from 'react'; import { View, Text, StyleSheet, Image } from 'react-native'; import SettlePosition from '../../../images/settlement/SettlePosition.png' import AddressUser from './AddressUser' import AddressText from './AddressText' import IconArrow from '../IconArrow' export default class AddressDetail extends Component { render() { let address = this.props.address return ( <View> <View style={styles.addressDetail}> {/* 收货人地址 */} <Image style={styles.settlePosition} source={SettlePosition}></Image> <AddressText style={styles.addressName}>北京市大兴区荣京中街朝林广场A座</AddressText> {/* 切换地址图标 */} <IconArrow style={styles.addressEdit} ></IconArrow> </View> <AddressUser address={address}></AddressUser> </View> ); } } const styles = StyleSheet.create({ addressDetail: { paddingHorizontal: 25, paddingTop: 15, // flex: 1, flexDirection: 'row', justifyContent: 'space-between' }, settlePosition: { width: 18, height: 18, marginRight: 10, marginTop: 3, }, addressName: { // flex: 1, }, addressEdit: { width: 16, height: 16, marginLeft: 35, marginTop: 3, }, });
lib/components/narrative/save-trip-button.js
opentripplanner/otp-react-redux
import React from 'react' import { OverlayTrigger, Tooltip } from 'react-bootstrap' import { FormattedMessage, useIntl } from 'react-intl' import { connect } from 'react-redux' import { LinkContainerWithQuery } from '../form/connected-links' import { CREATE_TRIP_PATH } from '../../util/constants' import Icon from '../util/icon' import { itineraryCanBeMonitored } from '../../util/itinerary' import { getActiveItinerary } from '../../util/state' /** * This connected component encapsulates the states and behavior of the button * to save an itinerary for notifications. */ const SaveTripButton = ({ itinerary, loggedInUser, persistence }) => { const intl = useIntl() // We are dealing with the following states: // 1. Persistence disabled => just return null // 2. User is not logged in => render something like: "Please sign in to save trip". // 3. itin cannot be monitored => disable the button with prompt and tooltip. let buttonDisabled let buttonText let tooltipText let iconType if (!persistence || !persistence.enabled) { return null } else if (!loggedInUser) { buttonDisabled = true buttonText = <FormattedMessage id='components.SaveTripButton.signInText' /> iconType = 'lock' tooltipText = intl.formatMessage({id: 'components.SaveTripButton.signInTooltip'}) } else if (!itineraryCanBeMonitored(itinerary)) { buttonDisabled = true buttonText = <FormattedMessage id='components.SaveTripButton.cantSaveText' /> iconType = 'ban' tooltipText = intl.formatMessage({id: 'components.SaveTripButton.cantSaveTooltip'}) } else { buttonText = <FormattedMessage id='components.SaveTripButton.saveTripText' /> iconType = 'plus-circle' } const button = ( <button // Apply pull-right style class so that the element is flush right, // even with LineItineraries. className='clear-button-formatting pull-right' disabled={buttonDisabled} style={buttonDisabled ? { pointerEvents: 'none' } : {}} > <Icon type={iconType} withSpace /> {buttonText} </button> ) // Show tooltip with help text if button is disabled. if (buttonDisabled) { return ( <OverlayTrigger overlay={( <Tooltip id='disabled-save-tooltip'> {/* Must get text using intl.formatMessage here because the rendering of OverlayTrigger seems to occur outside of the IntlProvider context. */} {tooltipText} </Tooltip> )} placement='top' > {/* An active element around the disabled button is necessary for the OverlayTrigger to render. */} <div className='pull-right' style={{ cursor: 'not-allowed' }}> {button} </div> </OverlayTrigger> ) } return ( <LinkContainerWithQuery to={CREATE_TRIP_PATH}> {button} </LinkContainerWithQuery> ) } // connect to the redux store const mapStateToProps = (state, ownProps) => { const { persistence } = state.otp.config return { itinerary: getActiveItinerary(state), loggedInUser: state.user.loggedInUser, persistence } } export default connect(mapStateToProps)(SaveTripButton)
fixtures/dom/src/components/fixtures/input-change-events/RangeKeyboardFixture.js
maxschmeling/react
import React from 'react'; import Fixture from '../../Fixture'; class RangeKeyboardFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { keydownCount: 0, changeCount: 0, }; } componentDidMount() { this.input.addEventListener('keydown', this.handleKeydown, false); } componentWillUnmount() { this.input.removeEventListener('keydown', this.handleKeydown, false); } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleKeydown = e => { // only interesting in arrow key events if ([37, 38, 39, 40].indexOf(e.keyCode) < 0) { return; } this.setState(({keydownCount}) => { return { keydownCount: keydownCount + 1, }; }); }; handleReset = () => { this.setState({ keydownCount: 0, changeCount: 0, }); }; render() { const {keydownCount, changeCount} = this.state; const color = keydownCount === changeCount ? 'green' : 'red'; return ( <Fixture> <div> <input type="range" ref={r => (this.input = r)} onChange={this.handleChange} /> <button onClick={() => this.input.focus()}> Focus Knob </button> </div> {' '} <p style={{color}}> <code>onKeyDown</code>{' calls: '}<strong>{keydownCount}</strong> {' vs '} <code>onChange</code>{' calls: '}<strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset counts</button> </Fixture> ); } } export default RangeKeyboardFixture;
app/jsx/gradebook-history/GradebookHistoryApp.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import { Provider } from 'react-redux'; import 'instructure-ui/lib/themes/canvas'; import I18n from 'i18n!gradebook_history'; import ScreenReaderContent from 'instructure-ui/lib/components/ScreenReaderContent'; import SearchForm from 'jsx/gradebook-history/SearchForm'; import SearchResults from 'jsx/gradebook-history/SearchResults'; import GradebookHistoryStore from 'jsx/gradebook-history/store/GradebookHistoryStore'; const GradebookHistoryApp = () => ( ( <Provider store={GradebookHistoryStore}> <div> <h1>{I18n.t('Gradebook History')}</h1> <SearchForm /> <SearchResults caption={<ScreenReaderContent>{I18n.t('Grade Changes')}</ScreenReaderContent>} /> </div> </Provider> ) ); export default GradebookHistoryApp;
react-flux-mui/js/material-ui/src/svg-icons/content/drafts.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentDrafts = (props) => ( <SvgIcon {...props}> <path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z"/> </SvgIcon> ); ContentDrafts = pure(ContentDrafts); ContentDrafts.displayName = 'ContentDrafts'; ContentDrafts.muiName = 'SvgIcon'; export default ContentDrafts;
Console/app/node_modules/rc-notification/es/Notification.js
RisenEsports/RisenEsports.github.io
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Animate from 'rc-animate'; import createChainedFunction from 'rc-util/es/createChainedFunction'; import classnames from 'classnames'; import Notice from './Notice'; var seed = 0; var now = Date.now(); function getUuid() { return 'rcNotification_' + now + '_' + seed++; } var Notification = function (_Component) { _inherits(Notification, _Component); function Notification() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Notification); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Notification.__proto__ || Object.getPrototypeOf(Notification)).call.apply(_ref, [this].concat(args))), _this), _this.state = { notices: [] }, _this.add = function (notice) { var key = notice.key = notice.key || getUuid(); _this.setState(function (previousState) { var notices = previousState.notices; if (!notices.filter(function (v) { return v.key === key; }).length) { return { notices: notices.concat(notice) }; } }); }, _this.remove = function (key) { _this.setState(function (previousState) { return { notices: previousState.notices.filter(function (notice) { return notice.key !== key; }) }; }); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Notification, [{ key: 'getTransitionName', value: function getTransitionName() { var props = this.props; var transitionName = props.transitionName; if (!transitionName && props.animation) { transitionName = props.prefixCls + '-' + props.animation; } return transitionName; } }, { key: 'render', value: function render() { var _this2 = this, _className; var props = this.props; var noticeNodes = this.state.notices.map(function (notice) { var onClose = createChainedFunction(_this2.remove.bind(_this2, notice.key), notice.onClose); return React.createElement( Notice, _extends({ prefixCls: props.prefixCls }, notice, { onClose: onClose }), notice.content ); }); var className = (_className = {}, _defineProperty(_className, props.prefixCls, 1), _defineProperty(_className, props.className, !!props.className), _className); return React.createElement( 'div', { className: classnames(className), style: props.style }, React.createElement( Animate, { transitionName: this.getTransitionName() }, noticeNodes ) ); } }]); return Notification; }(Component); Notification.propTypes = { prefixCls: PropTypes.string, transitionName: PropTypes.string, animation: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), style: PropTypes.object }; Notification.defaultProps = { prefixCls: 'rc-notification', animation: 'fade', style: { top: 65, left: '50%' } }; Notification.newInstance = function newNotificationInstance(properties) { var _ref2 = properties || {}, getContainer = _ref2.getContainer, props = _objectWithoutProperties(_ref2, ['getContainer']); var div = void 0; if (getContainer) { div = getContainer(); } else { div = document.createElement('div'); document.body.appendChild(div); } var notification = ReactDOM.render(React.createElement(Notification, props), div); return { notice: function notice(noticeProps) { notification.add(noticeProps); }, removeNotice: function removeNotice(key) { notification.remove(key); }, component: notification, destroy: function destroy() { ReactDOM.unmountComponentAtNode(div); if (!getContainer) { document.body.removeChild(div); } } }; }; export default Notification;
13-styling-css/src/Overlay.js
dtanzer/react-basic-examples
import React from 'react'; import { connect } from 'react-redux'; export class Overlay extends React.Component { render() { const display = this.props.overlay? "block" : "none"; const style = { background: "rgba(0, 0, 0, 0.5)", display: display, position: "absolute", top: 0, bottom: 0, left: 0, right: 0, zIndex: 1000 }; return ( <div style={style}> </div> ); } } function mapStateToProperties(state) { return { overlay: state.tabs.overlay }; } export const OverlayContainer = connect(mapStateToProperties)(Overlay);
src/components/CarCreate.js
brianyamasaki/rideshare
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { carCreate } from '../actions'; import { Card, CardSection, Button } from './common'; import CarForm from './CarForm'; class CarCreate extends Component { onButtonPress() { const { name, seats } = this.props; this.props.carCreate({ name, seats }); } render() { return ( <Card> <CarForm {...this.props} /> <CardSection> <Button onPress={this.onButtonPress.bind(this)}> Create </Button> </CardSection> </Card> ); } } const mapStateToProps = (state) => { const { name, seats } = state.car; return { name, seats }; }; export default connect(mapStateToProps, { carCreate })(CarCreate);
components/APP.js
endziu/game-init
'use strict' import React from 'react' import io from 'socket.io-client' import Header from './parts/Header' import Game from './game/Game' class APP extends React.Component { constructor () { super() this.state = { status: 'disconnected', error: '', currentUser: 'none', currentTeam: 'none', turn: 'none', players: [], walls: [], moves: [] } this.emit = this.emit.bind(this) } componentWillMount () { this.socket = io('localhost:3000') this.socket.on('connect', () => this.setState({ status: 'connected' })) this.socket.on('disconnect', () => this.setState({ status: 'disconnected' })) this.socket.on('error', (err) => this.setState({ error: err.mess })) this.socket.on('update', (x) => this.setState({ ...x })) } emit (eventName, payload) { this.socket.emit(eventName, payload) } render () { return ( <div> <Header {...this.state} /> <div className='game-container'> <Game emit={this.emit} {...this.state} /> </div> </div> ) } } module.exports = APP
app/containers/TrackPlayer/index.js
sedubois/belong
import React from 'react'; import Relay from 'react-relay'; import ReactPlayer from 'react-player'; import styles from './styles.css'; class TrackPlayer extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { viewer: React.PropTypes.shape({ Track: React.PropTypes.shape({ title: React.PropTypes.string.isRequired, url: React.PropTypes.string.isRequired, }).isRequired, }).isRequired, }; render() { return ( <div> <h1>{this.props.viewer.Track.title}</h1> <ReactPlayer className={styles.Track} url={this.props.viewer.Track.url} controls /> </div> ); } } export default Relay.createContainer(TrackPlayer, { initialVariables: { trackId: null, }, fragments: { viewer: () => Relay.QL` fragment on Viewer { Track(id: $trackId) { title url } } `, }, });
src/components/TransactionTableContainer.js
chatch/stellarexplorer
import React from 'react' import {compose} from 'recompose' import {withPaging} from './shared/Paging' import {withDataFetchingContainer} from './shared/DataFetchingContainer' import {withDataFetchingAllContainer} from './shared/DataFetchingAllContainer' import {isPublicKey} from '../lib/stellar/utils' import {isDefInt} from '../lib/utils' import TransactionTable from './TransactionTable' import CSVExport from './shared/CSVExport' const rspRecToPropsRec = rspRec => { return { hash: rspRec.hash, ledger: rspRec.ledger_attr, opCount: rspRec.operation_count, sourceAccount: rspRec.source_account, time: rspRec.created_at, } } const fetchRecords = props => { const builder = props.server.transactions() if (isDefInt(props, 'ledger')) builder.forLedger(props.ledger) if (isPublicKey(props.account)) builder.forAccount(props.account) builder.limit(props.limit) builder.order('desc') return builder.call() } const callBuilder = props => props.server.transactions() const enhance = compose( withPaging(), withDataFetchingContainer(fetchRecords, rspRecToPropsRec, callBuilder) ) const ExportToCSVComponent = withDataFetchingAllContainer(fetchRecords)( CSVExport ) const wrapHOC = Component => props => ( <div> <div> <Component {...props} /> </div> {!props.noCSVExport && ( <div className="text-center" id="csv-export"> <ExportToCSVComponent {...props} /> </div> )} </div> ) export default enhance(wrapHOC(TransactionTable))
src/renderer/components/bell-icon.js
sirbrillig/gitnews-menubar
import React from 'react'; export default function BellIcon({ className }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88.516 88.516" className={className}> <path d="M67.512 36.822C56.11 12.287 50.184 2.97 31.553 3.355c-6.635.137-5.041-4.805-10.1-2.93-5.055 1.876-.717 4.62-5.889 8.863C1.051 21.2 2.389 32.221 9.119 58.487c2.838 11.062-6.836 11.605-3.008 22.33 2.793 7.819 23.393 11.093 45.127 3.028 21.734-8.063 35.453-24.07 32.66-31.889-3.829-10.725-11.581-4.804-16.386-15.134zM48.879 77.238c-19.41 7.202-35.363 2.965-36.037 1.083-1.162-3.248 6.266-14.081 28.457-22.316 22.193-8.234 34.576-5.181 35.871-1.553.766 2.142-8.879 15.584-28.291 22.786zm-6.238-17.474C32.493 63.53 25.44 67.837 20.877 71.715c3.211 2.918 9.23 3.63 15.23 1.404 7.637-2.833 12.326-9.337 10.471-14.526-.021-.063-.055-.119-.078-.181a114.7 114.7 0 0 0-3.859 1.352z" fill="#030104" /> </svg> ); }
src/components/RegisterForm.js
jamez14/jams-tweeter
import React from 'react'; class RegisterForm extends React.Component { constructor(props) { super(props); } propTypes: { user: React.PropTypes.object.isRequired, errors: React.PropTypes.object.isRequired, onSave: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired } render() { return ( <form> <div className="form-group"> <label>Full Name</label> <input type="text" name="name" value={this.props.user.name} ref="name" onChange={this.props.onChange} /> </div> <div className="form-group"> <label>Username</label> <input type="text" name="handle" value={this.props.user.handle} ref="handle" onChange={this.props.onChange} /> </div> <div className="form-group"> <label>Location</label> <input type="text" name="location" value={this.props.user.location} ref="location" onChange={this.props.onChange} /> </div> <div className="error">{this.props.errors.name}</div> <div className="error">{this.props.errors.handle}</div> <button className="btn btn-primary" type="button" onClick={this.props.onSave}>Register</button> </form> ); } } export default RegisterForm;
client/node_modules/uu5g03/dist-node/common/lsi-mixin.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import Tools from './tools.js'; import $ from 'jquery'; export const LsiMixin = { //@@viewOn:statics statics: { UU5_Common_LsiMixin: { requiredMixins: ['UU5_Common_BaseMixin'], lsiEvent: Tools.events.lsi } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { language: React.PropTypes.string }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { language: null }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle getInitialState: function () { // initialize this.registerMixin('UU5_Common_LsiMixin'); // state return { language: this.props.language || this.getEnvironmentLanguages()[0].location || this.getEnvironmentLanguages()[0].language }; }, componentDidMount: function () { $(window).on(this.constructor.UU5_Common_LsiMixin.lsiEvent, this._changeLanguage); }, componentWillUnmount: function () { $(window).off(this.constructor.UU5_Common_LsiMixin.lsiEvent, this._changeLanguage); }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface hasUU5_Common_LsiMixin: function () { return this.hasMixin('UU5_Common_LsiMixin'); }, getUU5_Common_LsiMixinProps: function () { return { language: this.props.language }; }, getUU5_Common_LsiMixinPropsToPass: function () { return this.getUU5_Common_LsiMixinProps(); }, getLanguages: function () { return this.getEnvironmentLanguages(); }, getLanguage: function () { return this.state.language; }, // component gets languages from global environment getLSIItem: function (lsi) { return this.getLSIItemByLanguage(lsi, this.getLanguages()); }, //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers // TODO: 'cs-CZ,en;q=0.8...' is set to state and never will be used, necessary is doing setState and render the component _setLanguage: function (language, setStateCallback) { this.setState({ language: language }, setStateCallback); return this; }, _changeLanguage: function (e, language) { if (this.getLanguage() !== language) { if (typeof this.onChangeLanguage_ === 'function') { this.onChangeLanguage_(language, e); } else { this._setLanguage(language); } } } //@@viewOff:componentSpecificHelpers }; export default LsiMixin;
src/components/Guidelines/index.js
goodjoblife/GoodJobShare
import React from 'react'; import { Section, Wrapper } from 'common/base'; import PageBanner from 'common/PageBanner'; import editorStyles from 'common/Editor.module.css'; import StaticHelmet from 'common/StaticHelmet'; const GuideLines = () => ( <main> <StaticHelmet.Guidelines /> <PageBanner heading="發文留言規則" /> <Section padding> <Wrapper size="m" className={editorStyles.editor}> <p> GoodJob 的使用者您好!一旦您在 GoodJob 平台上發表內容(包含但不限於薪資及工時資訊、面試經驗分享、工作經驗分享、實習經驗分享、留言回覆以及檢舉的內容),即代表您同意遵守以下發文留言規則。我們未來有可能修訂本規則,您將會於本頁面或公告指定的頁面找到此規則的最新版本。 </p> <p> 您所發表的內容,若有以下情形之一者,本站管理者有權視情節輕重,隱藏或刪除該內容。 </p> <ol> <li> 包含針對特定族群之仇恨、威脅及歧視言論,含侮辱、挑撥、威脅、蓄意人身攻擊、歧視等文字。特定族群包含但不限於種族、地域、職業、公司、性別、年齡、學校、薪水階級等族群。 </li> <li> 包含違反中華民國法律之內容。例如:散布他人個人隱私資訊、侵害他人著作權之內容、惡意程式之網站連結。 </li> <li>內容主要為商業廣告之用途。</li> <li>相同內容重複張貼。</li> <li> 內容包含不易閱讀之資訊。例如:注音文、未註明用途之超連結。意即,超連結須註明來源。 </li> <li> 內容指涉之資訊,顯然不具參考性,或顯然有誤。例如:公司或職務名稱無法辨識、薪資數額明顯不合理。 </li> <li> 職場經驗之分享的本文字數若低於(含) 50 字,則本版管理團隊可依內容相關程度判斷是否保留/刪除。 </li> <li>與本版宗旨或本討論串無相關之內容。</li> </ol> </Wrapper> </Section> </main> ); export default GuideLines;
client/src/components/landing/components/Testimonials.js
raisedadead/FreeCodeCamp
import PropTypes from 'prop-types'; import React from 'react'; import { Trans, useTranslation } from 'react-i18next'; import emmaImg from '../../../assets/images/landing/Emma.png'; import sarahImg from '../../../assets/images/landing/Sarah.png'; import shawnImg from '../../../assets/images/landing/Shawn.png'; import { ImageLoader } from '../../helpers'; const propTypes = { page: PropTypes.string }; const Testimonials = () => { const { t } = useTranslation(); return ( <div className='testimonials'> <h1 className='big-heading text-center'> {t('landing.testimonials.heading')} </h1> <div className='testimonials-row' data-test-label='testimonial-cards'> <div className='testimonial-card'> <div className='testimonial-card-header'> <ImageLoader alt='Shawn Wang' className='testimonial-image' src={shawnImg} /> </div> <div className='testimonials-footer'> <div className='testimonial-meta'> <p> {' '} <Trans>landing.testimonials.shawn.location</Trans> </p> <p> <Trans>landing.testimonials.shawn.occupation</Trans> </p> </div> <div className='testimony'> <p> <Trans>landing.testimonials.shawn.testimony</Trans> </p> </div> </div> </div> <div className='testimonial-card'> <div className='testimonial-card-header'> <ImageLoader alt='Sarah Chima' className='testimonial-image' src={sarahImg} /> </div> <div className='testimonials-footer'> <div className='testimonial-meta'> <p> {' '} <Trans>landing.testimonials.sarah.location</Trans> </p> <p> <Trans>landing.testimonials.sarah.occupation</Trans> </p> </div> <div className='testimony'> <p> <Trans>landing.testimonials.sarah.testimony</Trans> </p> </div> </div> </div> <div className='testimonial-card'> <div className='testimonial-card-header'> <ImageLoader alt='Emma Bostian' className='testimonial-image' src={emmaImg} /> </div> <div className='testimonials-footer'> <div className='testimonial-meta'> <p> {' '} <Trans>landing.testimonials.emma.location</Trans> </p> <p> <Trans>landing.testimonials.emma.occupation</Trans> </p> </div> <div className='testimony'> <p> <Trans>landing.testimonials.emma.testimony</Trans> </p> </div> </div> </div> </div> </div> ); }; Testimonials.displayName = 'Testimonals'; Testimonials.propTypes = propTypes; export default Testimonials;
src/svg-icons/content/add.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAdd = (props) => ( <SvgIcon {...props}> <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/> </SvgIcon> ); ContentAdd = pure(ContentAdd); ContentAdd.displayName = 'ContentAdd'; ContentAdd.muiName = 'SvgIcon'; export default ContentAdd;
src/esm/components/structure/cards/reward-card/components/info.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["className", "legend", "value", "fullWidth"]; import React from 'react'; import classNames from 'classnames'; import { Text } from '../../../../typography/text'; export var Info = function Info(_ref) { var className = _ref.className, legend = _ref.legend, value = _ref.value, _ref$fullWidth = _ref.fullWidth, fullWidth = _ref$fullWidth === void 0 ? false : _ref$fullWidth, props = _objectWithoutPropertiesLoose(_ref, _excluded); console.warn('This subcomponent is deprecated. Please use another one.'); return /*#__PURE__*/React.createElement("p", _extends({ className: classNames('k-RewardCard__info', 'k-u-size-small', 'k-u-line-height-normal', className, { 'k-RewardCard__halfDrawer': !fullWidth, 'k-RewardCard__drawer': fullWidth }) }, props), /*#__PURE__*/React.createElement(Text, { className: "k-RewardCard__info__legend", weight: "regular", size: "small", lineHeight: "normal" }, legend), ' ', /*#__PURE__*/React.createElement(Text, { className: "k-RewardCard__info__value", weight: "light", size: "small", lineHeight: "normal" }, value)); };
app/components/Pagination/index.js
54vanya/ru-for-you-front
import React from 'react'; import Page from './Page'; import styled from 'styled-components'; const Wrapper = styled.div` display:flex; flex-wrap:wrap; margin:8px; &>*{ margin:0 8px; } `; const Pagination = ({ pages, page, onClick }) => { const elements = pages ? [] : null; if (pages > 1) { for (let i = 0; i < pages; i++) { elements.push(<Page key={`page-${i}`} n={i} onClick={onClick} isActive={page === i} />); } } return ( <Wrapper> {elements} </Wrapper> ); }; Pagination.propTypes = { pages: React.PropTypes.number.isRequired, page: React.PropTypes.number.isRequired, onClick: React.PropTypes.func.isRequired, }; export default Pagination;
src/app/_server.js
coltpini/react-demo-site
import React from 'react'; import docTemplate from './HTML.js'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import { Provider } from 'react-redux'; import Helmet from 'react-helmet'; import routes from './routes.js'; import getStore from './store/index.js'; import { minify } from 'html-minifier'; import { resolve } from './lib/ss-resolve'; import {DEV_ENDPOINT_BASE} from './env.js'; export default (req, res, next) => { match({ routes, location: req.url }, (err, redirect, props) => { if (err) { return next(err); } else if (redirect) { res.redirect(redirect.pathname + redirect.search) } else if (props) { const store = getStore(); resolve(props, store) .then(() => { const initialState = store.getState(); const content = renderToString( <Provider store={store}> <RouterContext {...props} /> </Provider> ); res.send( minify( docTemplate({ ...(Helmet.rewind()), content, initialState, env: {DEV_ENDPOINT_BASE} }), { collapseWhitespace: true, removeAttributeQuotes: true } ) ); }).catch(next); } else { res.status(404).send('Not Found') } }) }
app/javascript/mastodon/features/ui/components/video_modal.js
RobertRence/Mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Video from '../../video'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class VideoModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, time: PropTypes.number, onClose: PropTypes.func.isRequired, }; render () { const { media, time, onClose } = this.props; return ( <div className='modal-root__modal media-modal'> <div> <Video preview={media.get('preview_url')} src={media.get('url')} startTime={time} onCloseVideo={onClose} /> </div> </div> ); } }
node_modules/rc-animate/es/ChildrenUtils.js
ZSMingNB/react-news
import React from 'react'; export function toArrayChildren(children) { var ret = []; React.Children.forEach(children, function (child) { ret.push(child); }); return ret; } export function findChildInChildrenByKey(children, key) { var ret = null; if (children) { children.forEach(function (child) { if (ret) { return; } if (child && child.key === key) { ret = child; } }); } return ret; } export function findShownChildInChildrenByKey(children, key, showProp) { var ret = null; if (children) { children.forEach(function (child) { if (child && child.key === key && child.props[showProp]) { if (ret) { throw new Error('two child with same key for <rc-animate> children'); } ret = child; } }); } return ret; } export function findHiddenChildInChildrenByKey(children, key, showProp) { var found = 0; if (children) { children.forEach(function (child) { if (found) { return; } found = child && child.key === key && !child.props[showProp]; }); } return found; } export function isSameChildren(c1, c2, showProp) { var same = c1.length === c2.length; if (same) { c1.forEach(function (child, index) { var child2 = c2[index]; if (child && child2) { if (child && !child2 || !child && child2) { same = false; } else if (child.key !== child2.key) { same = false; } else if (showProp && child.props[showProp] !== child2.props[showProp]) { same = false; } } }); } return same; } export function mergeChildren(prev, next) { var ret = []; // For each key of `next`, the list of keys to insert before that key in // the combined list var nextChildrenPending = {}; var pendingChildren = []; prev.forEach(function (child) { if (child && findChildInChildrenByKey(next, child.key)) { if (pendingChildren.length) { nextChildrenPending[child.key] = pendingChildren; pendingChildren = []; } } else { pendingChildren.push(child); } }); next.forEach(function (child) { if (child && nextChildrenPending.hasOwnProperty(child.key)) { ret = ret.concat(nextChildrenPending[child.key]); } ret.push(child); }); ret = ret.concat(pendingChildren); return ret; }
packages/frontend/src/App.js
ehawk61/AngularJSApp
import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
src/modules/chat/chatMain/components/PostConnect.js
Florenz23/sangoo_04
import React from 'react' import { StyleSheet , Text } from 'react-native' const PostConnect = (props) => { return ( <Text> Connect </Text> ) } export default PostConnect
src/svg-icons/av/art-track.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvArtTrack = (props) => ( <SvgIcon {...props}> <path d="M22 13h-8v-2h8v2zm0-6h-8v2h8V7zm-8 10h8v-2h-8v2zm-2-8v6c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2zm-1.5 6l-2.25-3-1.75 2.26-1.25-1.51L3.5 15h7z"/> </SvgIcon> ); AvArtTrack = pure(AvArtTrack); AvArtTrack.displayName = 'AvArtTrack'; AvArtTrack.muiName = 'SvgIcon'; export default AvArtTrack;
packages/recon-engine/src/engine/__tests__/__fixtures__/basic-app/src/notes.js
recon-js/recon
/* eslint-disable */ import React from 'react'; import List, {ListItem} from './list'; import {createContainer, query as q} from 'api/recall'; import {Note} from 'api/resources'; function NoteItem({note}) { return ( <ListItem type="grid"> <Avatar src={note.created_by.img} /> <p>{note.content}</p> </ListItem> ); } export function Notes({notes}) { return ( <div> <h2>Notes</h2> <List type="grid"> {notes.map(user => { return <NoteItem note={note} key={user.id} />; })} </List> </div> ); } const contain = createContainer({ queries: { invoices: q.many(Note, { params: vars => ({ filter: { parent: vars.parent, }, }), fields: { content: true, created_by: { img: true, }, }, }), }, }); export default contain(Notes);
node_modules/@material-ui/core/es/CardMedia/CardMedia.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import warning from 'warning'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: { display: 'block', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' }, /* Styles applied to the root element if `component="video, audio, picture, iframe, or img"`. */ media: { width: '100%', // ⚠️ object-fit is not supported by IE 11. objectFit: 'cover' } }; const MEDIA_COMPONENTS = ['video', 'audio', 'picture', 'iframe', 'img']; const CardMedia = React.forwardRef(function CardMedia(props, ref) { const { classes, className, component: Component = 'div', image, src, style } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "component", "image", "src", "style"]); process.env.NODE_ENV !== "production" ? warning(Boolean(image || src), 'Material-UI: either `image` or `src` property must be specified.') : void 0; const isMediaComponent = MEDIA_COMPONENTS.indexOf(Component) !== -1; const composedStyle = !isMediaComponent && image ? _extends({ backgroundImage: `url("${image}")` }, style) : style; return React.createElement(Component, _extends({ className: clsx(classes.root, isMediaComponent && classes.media, className), ref: ref, style: composedStyle, src: isMediaComponent ? image || src : undefined }, other)); }); process.env.NODE_ENV !== "production" ? CardMedia.propTypes = { /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Component for rendering image. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * Image to be displayed as a background image. * Either `image` or `src` prop must be specified. * Note that caller must specify height otherwise the image will not be visible. */ image: PropTypes.string, /** * An alias for `image` property. * Available only with media components. * Media components: `video`, `audio`, `picture`, `iframe`, `img`. */ src: PropTypes.string, /** * @ignore */ style: PropTypes.object } : void 0; export default withStyles(styles, { name: 'MuiCardMedia' })(CardMedia);
app/scripts/components/soundItem/soundItem.js
bluedaniel/Kakapo-app
import React from 'react'; import { prop } from 'ramda'; import { soundActions } from 'actions/'; import { cx, handleStopPropagation, openLink } from 'utils/'; import './soundItem.css'; export default ({ sound, themes, dispatch }) => { const handleToggle = () => dispatch(soundActions.play(sound)); const handleDelete = el => { handleStopPropagation(el); dispatch(soundActions.remove(sound)); }; const handleEdit = el => { handleStopPropagation(el); dispatch(soundActions.edit(sound)); }; const renderActions = () => ( <div className={cx('actions', { dark: !sound.playing })}> {sound.link ? ( <div> <a href={sound.link} onClick={e => openLink(e, sound.link)} rel="noopener noreferrer" target="_blank" > <i className="icon-share" /> </a> </div> ) : ( '' )} {sound.source !== 'youtubeStream' ? ( <div role="presentation" onClick={handleEdit}> <i className="icon-edit" /> </div> ) : ( '' )} <div role="presentation" onClick={handleDelete}> <i className="icon-delete" /> </div> </div> ); let objStyle = { color: '#121212' }; if (sound.playing) { objStyle = { ...objStyle, backgroundColor: prop('primary', themes), color: '#fff', }; } let icon; if (sound.source === 'file') { icon = <i className={cx('preview', `icon-${sound.img}`)} />; } else { icon = sound.img ? ( <img src={sound.img} alt={sound.name} /> ) : ( <div className="no-image" /> ); } return ( <div onClick={handleToggle} style={objStyle} role="button" tabIndex={-1} className={cx('item', 'waves-effect', 'waves-block', { playing: sound.playing, paused: !sound.playing, 'youtube-stream': sound.source === 'youtubeStream', })} > <div className="inner"> {icon} {renderActions()} <span className="title">{sound.name}</span> <input defaultValue={sound.volume} max="1" min="0" step="0.01" type="range" onChange={({ target: { value } }) => dispatch(soundActions.throttleVolume(sound, parseFloat(value))) } onClick={handleStopPropagation} /> </div> {sound.source === 'youtubeStream' ? ( <div className="youtube-video" id={`video-${sound.file}`} /> ) : ( <div /> )} </div> ); };