path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/clients/next/components/dropzone.js
garbin/koapp
import React from 'react' import Dropzone from 'react-dropzone' import { connect } from 'react-redux' import { api } from '../redux/actions' export default function dropzone (options) { const { onSuccess = console.log, onError = console.error, mapStateToProps = state => ({api: state.api}), keyName = 'files', ...others } = options return Component => { return connect(mapStateToProps)(props => { const { dispatch, refCallback, api: apiState, ...othersProps } = props const upload = files => { return Promise.all(files.map((file, idx) => { const data = new window.FormData() data.append('file', file, file.name) return dispatch(api.post(`${keyName}_${idx}`)('/files', data, { headers: { 'content-type': 'multipart/form-data' } })) })).then(onSuccess).catch(onError) } return ( <Dropzone style={{}} onDrop={upload} ref={refCallback} {...othersProps} {...others}> {status => <Component status={status} />} </Dropzone> ) }) } }
src/svg-icons/notification/wc.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationWc = (props) => ( <SvgIcon {...props}> <path d="M5.5 22v-7.5H4V9c0-1.1.9-2 2-2h3c1.1 0 2 .9 2 2v5.5H9.5V22h-4zM18 22v-6h3l-2.54-7.63C18.18 7.55 17.42 7 16.56 7h-.12c-.86 0-1.63.55-1.9 1.37L12 16h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z"/> </SvgIcon> ); NotificationWc = pure(NotificationWc); NotificationWc.displayName = 'NotificationWc'; NotificationWc.muiName = 'SvgIcon'; export default NotificationWc;
src/client/story_box.js
2braincells2go/hacker-menu
import React from 'react' import _ from 'lodash' import Client from 'electron-rpc/client' import StoryList from './story_list.js' import Spinner from './spinner.js' import Menu from './menu.js' import StoryType from '../model/story_type' export default class StoryBox extends React.Component { constructor (props) { super(props) this.client = new Client() this.state = { stories: [], selected: StoryType.TOP_TYPE, status: '', version: '', upgradeVersion: '' } } componentDidMount () { var self = this self.client.request('current-version', function (err, version) { if (err) { console.error(err) return } self.setState({ version: version }) }) self.onNavbarClick(self.state.selected) } onQuitClick () { this.client.request('terminate') } onUrlClick (url) { this.client.request('open-url', { url: url }) } onMarkAsRead (id) { this.client.request('mark-as-read', { id: id }, function () { var story = _.findWhere(this.state.stories, { id: id }) story.hasRead = true this.setState({ stories: this.state.stories }) }.bind(this)) } onNavbarClick (selected) { var self = this self.setState({ stories: [], selected: selected }) self.client.localEventEmitter.removeAllListeners() self.client.on('update-available', function (err, releaseVersion) { if (err) { console.error(err) return } self.setState({ status: 'update-available', upgradeVersion: releaseVersion }) }) var storycb = function (err, storiesMap) { if (err) { return } // console.log(JSON.stringify(Object.keys(storiesMap), null, 2)) var stories = storiesMap[self.state.selected] if (!stories) { return } // console.log(JSON.stringify(stories, null, 2)) self.setState({stories: stories}) } self.client.request(selected, storycb) self.client.on(selected, storycb) } render () { var navNodes = _.map(StoryType.ALL, function (selection) { var className = 'control-item' if (this.state.selected === selection) { className = className + ' active' } return ( <a key={selection} className={className} onClick={this.onNavbarClick.bind(this, selection)}>{selection}</a> ) }, this) var content = null if (_.isEmpty(this.state.stories)) { content = <Spinner /> } else { content = <StoryList stories={this.state.stories} onUrlClick={this.onUrlClick.bind(this)} onMarkAsRead={this.onMarkAsRead.bind(this)} /> } return ( <div className='story-menu'> <header className='bar bar-nav'> <div className='segmented-control'> {navNodes} </div> </header> {content} <Menu onQuitClick={this.onQuitClick.bind(this)} status={this.state.status} version={this.state.version} upgradeVersion={this.state.upgradeVersion} /> </div> ) } }
src/parser/druid/restoration/modules/talents/Flourish.js
fyruna/WoWAnalyzer
import React from 'react'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import StatisticBox from 'interface/others/StatisticBox'; import { formatPercentage, formatNumber } from 'common/format'; import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import HotTracker from '../core/hottracking/HotTracker'; import { HOTS_AFFECTED_BY_ESSENCE_OF_GHANIR } from '../../constants'; const debug = false; const FLOURISH_EXTENSION = 8000; const FLOURISH_HEALING_INCREASE = 1; /* Extends the duration of all of your heal over time effects on friendly targets within 60 yards by 8 sec, and increases the rate of your heal over time effects by 100% for 8 sec. */ // TODO: Idea - Give suggestions on low amount/duration extended with flourish on other HoTs class Flourish extends Analyzer { static dependencies = { hotTracker: HotTracker, }; // Counters for hot extension flourishCount = 0; flourishes = []; wgsExtended = 0; // tracks how many flourishes extended Wild Growth cwsExtended = 0; // tracks how many flourishes extended Cenarion Ward tranqsExtended = 0; hasCenarionWard = false; rejuvCount = 0; wgCount = 0; lbCount = 0; regrowthCount = 0; sbCount = 0; cultCount = 0; tranqCount = 0; groveTendingCount = 0; // Counters for increased ticking rate of hots increasedRateTotalHealing = 0; increasedRateRejuvenationHealing = 0; increasedRateWildGrowthHealing = 0; increasedRateCenarionWardHealing = 0; increasedRateCultivationHealing = 0; increasedRateLifebloomHealing = 0; increasedRateRegrowthHealing = 0; increasedRateTranqHealing = 0; increasedRateGroveTendingHealing = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.FLOURISH_TALENT.id); this.hasCenarionWard = this.selectedCombatant.hasTalent(SPELLS.CENARION_WARD_TALENT.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (this.selectedCombatant.hasBuff(SPELLS.FLOURISH_TALENT.id) && HOTS_AFFECTED_BY_ESSENCE_OF_GHANIR.includes(spellId)) { switch (spellId) { case SPELLS.REJUVENATION.id: this.increasedRateRejuvenationHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.REJUVENATION_GERMINATION.id: this.increasedRateRejuvenationHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.WILD_GROWTH.id: this.increasedRateWildGrowthHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.CENARION_WARD_HEAL.id: this.increasedRateCenarionWardHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.CULTIVATION.id: this.increasedRateCultivationHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.LIFEBLOOM_HOT_HEAL.id: this.increasedRateLifebloomHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.GROVE_TENDING.id: this.increasedRateGroveTendingHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); break; case SPELLS.REGROWTH.id: if (event.tick === true) { this.increasedRateRegrowthHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); } break; case SPELLS.TRANQUILITY_HEAL.id: if (event.tick === true) { this.increasedRateTranqHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); } break; default: console.error('EssenceOfGhanir: Error, could not identify this object as a HoT: %o', event); } if ((SPELLS.REGROWTH.id === spellId || SPELLS.TRANQUILITY_HEAL.id) && event.tick !== true) { return; } this.increasedRateTotalHealing += calculateEffectiveHealing(event, FLOURISH_HEALING_INCREASE); } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (SPELLS.FLOURISH_TALENT.id !== spellId) { return; } this.flourishCount += 1; debug && console.log(`Flourish cast #: ${this.flourishCount}`); const newFlourish = { name: `Flourish #${this.flourishCount}`, healing: 0, masteryHealing: 0, procs: 0, duration: 0, }; this.flourishes.push(newFlourish); let foundWg = false; let foundCw = false; let foundTranq = false; Object.keys(this.hotTracker.hots).forEach(playerId => { Object.keys(this.hotTracker.hots[playerId]).forEach(spellIdString => { const spellId = Number(spellIdString); // due to flourish's refresh mechanc, we don't include it in Flourish numbers const attribution = spellId === SPELLS.CULTIVATION.id ? null : newFlourish; this.hotTracker.addExtension(attribution, FLOURISH_EXTENSION, playerId, spellId); if (spellId === SPELLS.WILD_GROWTH.id) { foundWg = true; this.wgCount += 1; } else if (spellId === SPELLS.CENARION_WARD_HEAL.id) { foundCw = true; } else if (spellId === SPELLS.REJUVENATION.id || spellId === SPELLS.REJUVENATION_GERMINATION.id) { this.rejuvCount += 1; } else if (spellId === SPELLS.REGROWTH.id) { this.regrowthCount += 1; } else if (spellId === SPELLS.LIFEBLOOM_HOT_HEAL.id) { this.lbCount += 1; } else if (spellId === SPELLS.SPRING_BLOSSOMS.id) { this.sbCount += 1; } else if (spellId === SPELLS.CULTIVATION.id) { this.cultCount += 1; } else if (spellId === SPELLS.GROVE_TENDING.id) { this.groveTendingCount += 1; } else if (spellId === SPELLS.TRANQUILITY_HEAL.id) { foundTranq = true; this.tranqCount += 1; } }); }); if (foundWg) { this.wgsExtended += 1; } if (foundCw) { this.cwsExtended += 1; } if (foundTranq) { this.tranqsExtended += 1; } } get totalExtensionHealing() { return this.flourishes.reduce((acc, flourish) => acc + flourish.healing + flourish.masteryHealing, 0); } get averageHealing() { return this.flourishCount === 0 ? 0 : this.totalExtensionHealing / this.flourishCount; } get percentWgsExtended() { return this.flourishCount === 0 ? 0 : this.wgsExtended / this.flourishCount; } get wildGrowthSuggestionThresholds() { return { actual: this.percentWgsExtended, isLessThan: { minor: 1.00, average: 0.75, major: 0.50, }, style: 'percentage', }; } get percentCwsExtended() { return (this.cwsExtended / this.flourishCount) || 0; } get cenarionWardSuggestionThresholds() { return { actual: this.percentCwsExtended, isLessThan: { minor: 1.00, average: 0.00, major: 0.00, }, style: 'percentage', }; } suggestions(when) { if(this.flourishCount === 0) { return; } when(this.wildGrowthSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.FLOURISH_TALENT.id} /> should always aim to extend a <SpellLink id={SPELLS.WILD_GROWTH.id} /></>) .icon(SPELLS.FLOURISH_TALENT.icon) .actual(`${formatPercentage(this.wgsExtended / this.flourishCount, 0)}% WGs extended.`) .recommended(`${formatPercentage(recommended)}% is recommended`); }); if(this.hasCenarionWard) { when(this.cenarionWardSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.FLOURISH_TALENT.id} /> should always aim to extend a <SpellLink id={SPELLS.CENARION_WARD_HEAL.id} /></>) .icon(SPELLS.FLOURISH_TALENT.icon) .actual(`${this.cwsExtended}/${this.flourishCount} CWs extended.`) .recommended(`${formatPercentage(recommended)}% is recommended`); }); } } statistic() { const extendPercent = this.owner.getPercentageOfTotalHealingDone(this.totalExtensionHealing); const increasedRatePercent = this.owner.getPercentageOfTotalHealingDone(this.increasedRateTotalHealing); const totalPercent = this.owner.getPercentageOfTotalHealingDone(this.totalExtensionHealing + this.increasedRateTotalHealing); return( <StatisticBox icon={<SpellIcon id={SPELLS.FLOURISH_TALENT.id} />} value={`${formatPercentage(totalPercent)} %`} label="Flourish Healing" tooltip={( <> The HoT extension contributed: <strong>{formatPercentage(extendPercent)} %</strong><br /> The HoT increased tick rate contributed: <strong>{formatPercentage(increasedRatePercent)} %</strong><br /> <ul> {this.wildGrowth !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateWildGrowthHealing))}% from Wild Growth</li>} {this.rejuvenation !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateRejuvenationHealing))}% from Rejuvenation</li>} {this.cenarionWard !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateCenarionWardHealing))}% from Cenarion Ward</li>} {this.lifebloom !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateLifebloomHealing))}% from Lifebloom</li>} {this.regrowth !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateRegrowthHealing))}% from Regrowth</li>} {this.cultivation !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateCultivationHealing))}% from Cultivation</li>} {this.traquility !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateTranqHealing))}% from Tranquillity</li>} {this.groveTending !== 0 && <li>{formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.increasedRateGroveTendingHealing))}% from Grove Tending</li>} </ul> The per Flourish amounts do <em>not</em> include Cultivation due to its refresh mechanic.<br /> Your {this.flourishCount} Flourish casts extended: <ul> <li>{this.wgsExtended}/{this.flourishCount} Wild Growth casts ({this.wgCount} HoTs)</li> {this.hasCenarionWard && <li>{this.cwsExtended}/{this.flourishCount} Cenarion Wards</li>} {this.rejuvCount > 0 && <li>{this.rejuvCount} Rejuvenations</li>} {this.regrowthCount > 0 && <li>{this.regrowthCount} Regrowths</li>} {this.lbCount > 0 && <li>{this.lbCount} Lifeblooms</li>} {this.sbCount > 0 && <li>{this.sbCount} Spring Blossoms</li>} {this.cultCount > 0 && <li>{this.cultCount} Cultivations (not counted in HoT count and HoT healing totals)</li>} {this.tranqCount > 0 && <li>{this.tranqsExtended}/{this.flourishCount} Tranquillities casts ({this.tranqCount} HoTs)</li>} {this.groveTendingCount > 0 && <li>{this.groveTendingCount}/{this.flourishCount} Grove tendings</li>} </ul> <br /> The Healing column shows how much additional healing was done by the 8 extra seconds of HoT time. Note that if you Flourished near the end of a fight, numbers might be lower than you expect because extension healing isn't tallied until a HoT falls. </> )} > <table className="table table-condensed"> <thead> <tr> <th>Cast</th> <th># of HoTs</th> <th>Healing</th> </tr> </thead> <tbody> { this.flourishes.map((flourish, index) => ( <tr key={index}> <th scope="row">{ index + 1 }</th> <td>{ flourish.procs }</td> <td>{ formatNumber(flourish.healing + flourish.masteryHealing) }</td> </tr> )) } </tbody> </table> </StatisticBox> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(); } export default Flourish;
app/jsx/gradebook-history/SearchForm.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, { Component } from 'react'; import { connect } from 'react-redux'; import { arrayOf, func, shape, string } from 'prop-types'; import I18n from 'i18n!gradebook_history'; import moment from 'moment'; import Autocomplete from 'instructure-ui/lib/components/Autocomplete'; import Button from 'instructure-ui/lib/components/Button'; import Container from 'instructure-ui/lib/components/Container'; import DateInput from 'instructure-ui/lib/components/DateInput'; import FormFieldGroup from 'instructure-ui/lib/components/FormFieldGroup'; import Spinner from 'instructure-ui/lib/components/Spinner'; import ScreenReaderContent from 'instructure-ui/lib/components/ScreenReaderContent'; import SearchFormActions from 'jsx/gradebook-history/actions/SearchFormActions'; import { showFlashAlert } from 'jsx/shared/FlashAlert'; const recordShape = shape({ fetchStatus: string.isRequired, items: arrayOf(shape({ id: string.isRequired, name: string.isRequired })), nextPage: string.isRequired }); class SearchFormComponent extends Component { static propTypes = { fetchHistoryStatus: string.isRequired, assignments: recordShape.isRequired, graders: recordShape.isRequired, students: recordShape.isRequired, getGradebookHistory: func.isRequired, clearSearchOptions: func.isRequired, getSearchOptions: func.isRequired, getSearchOptionsNextPage: func.isRequired, }; state = { selected: { assignment: '', grader: '', student: '', from: '', to: '' }, messages: { assignments: I18n.t('Type a few letters to start searching'), graders: I18n.t('Type a few letters to start searching'), students: I18n.t('Type a few letters to start searching') } }; componentDidMount () { this.props.getGradebookHistory(this.state.selected); } componentWillReceiveProps ({ fetchHistoryStatus, assignments, graders, students }) { if (this.props.fetchHistoryStatus === 'started' && fetchHistoryStatus === 'failure') { showFlashAlert({ message: I18n.t('Error loading gradebook history. Try again?') }); } if (assignments.fetchStatus === 'success' && assignments.items.length === 0) { this.setState(prevState => ({ messages: { ...prevState.messages, assignments: I18n.t('No assignments with that name found') } })); } if (graders.fetchStatus === 'success' && !graders.items.length) { this.setState(prevState => ({ messages: { ...prevState.messages, graders: I18n.t('No graders with that name found') } })); } if (students.fetchStatus === 'success' && !students.items.length) { this.setState(prevState => ({ messages: { ...prevState.messages, students: I18n.t('No students with that name found') } })); } if (assignments.nextPage) { this.props.getSearchOptionsNextPage('assignments', assignments.nextPage); } if (graders.nextPage) { this.props.getSearchOptionsNextPage('graders', graders.nextPage); } if (students.nextPage) { this.props.getSearchOptionsNextPage('students', students.nextPage); } } setSelectedFrom = (_, from) => { const startOfFrom = from ? moment(from).startOf('day').format() : ''; this.setState(prevState => ({ selected: { ...prevState.selected, from: startOfFrom } })); } setSelectedTo = (_, to) => { const endOfTo = to ? moment(to).endOf('day').format() : ''; this.setState(prevState => ({ selected: { ...prevState.selected, to: endOfTo } })); } setSelectedAssignment = (event, selected) => { this.props.clearSearchOptions('assignments'); this.setState(prevState => ({ selected: { ...prevState.selected, assignment: selected ? selected.id : '' } })); } setSelectedGrader = (event, selected) => { this.props.clearSearchOptions('graders'); this.setState(prevState => ({ selected: { ...prevState.selected, grader: selected ? selected.id : '' } })); } setSelectedStudent = (event, selected) => { this.props.clearSearchOptions('students'); this.setState(prevState => ({ selected: { ...prevState.selected, student: selected ? selected.id : '' } })); } hasToBeforeFrom () { return moment(this.state.selected.from).diff(moment(this.state.selected.to), 'seconds') >= 0; } hasDateInputErrors () { return this.dateInputErrors().length > 0; } dateInputErrors = () => { if (this.hasToBeforeFrom()) { return [{ type: 'error', text: I18n.t('\'From\' date must be before \'To\' date') }]; } return []; } promptUserEntry = () => { const emptyMessage = I18n.t('Type a few letters to start searching'); this.setState({ messages: { assignments: emptyMessage, graders: emptyMessage, students: emptyMessage } }); } handleSearchEntry = (event) => { const target = event.target.id; const searchTerm = event.target.value; if (searchTerm.length <= 2) { if (this.props[target].items.length > 0) { this.props.clearSearchOptions(target); this.promptUserEntry(); } return; } this.props.getSearchOptions(target, searchTerm); } handleSubmit = () => { this.props.getGradebookHistory(this.state.selected); } filterNone = options => ( // empty function here as the default filter function for Autocomplete // does a startsWith call, and won't match `nora` -> `Elenora` for example options ) renderAsOptions = data => ( data.map(item => ( <option key={item.id} value={item.id}>{item.name}</option> )) ) render () { return ( <Container as="div" margin="0 0 xx-large x-small"> <FormFieldGroup description={<ScreenReaderContent>{I18n.t('Search Form')}</ScreenReaderContent>} as="div" layout="columns" colSpacing="large" vAlign="top" startAt="large" > <FormFieldGroup description={<ScreenReaderContent>{I18n.t('Users')}</ScreenReaderContent>} as="div" layout="columns" vAlign="top" startAt="medium" > <Autocomplete id="students" allowEmpty emptyOption={this.state.messages.students} filter={this.filterNone} label={I18n.t('Student')} loading={this.props.students.fetchStatus === 'started'} loadingOption={<Spinner size="small" title={I18n.t('Loading Students')} />} onBlur={this.promptUserEntry} onChange={this.setSelectedStudent} onInputChange={this.handleSearchEntry} > {this.renderAsOptions(this.props.students.items)} </Autocomplete> <Autocomplete id="graders" allowEmpty emptyOption={this.state.messages.graders} filter={this.filterNone} label={I18n.t('Grader')} loading={this.props.graders.fetchStatus === 'started'} loadingOption={<Spinner size="small" title={I18n.t('Loading Graders')} />} onBlur={this.promptUserEntry} onChange={this.setSelectedGrader} onInputChange={this.handleSearchEntry} > {this.renderAsOptions(this.props.graders.items)} </Autocomplete> <Autocomplete id="assignments" allowEmpty emptyOption={this.state.messages.assignments} filter={this.filterNone} label={I18n.t('Assignment')} loading={this.props.assignments.fetchStatus === 'started'} loadingOption={<Spinner size="small" title={I18n.t('Loading Assignments')} />} onBlur={this.promptUserEntry} onChange={this.setSelectedAssignment} onInputChange={this.handleSearchEntry} > {this.renderAsOptions(this.props.assignments.items)} </Autocomplete> </FormFieldGroup> <FormFieldGroup description={<ScreenReaderContent>{I18n.t('Dates')}</ScreenReaderContent>} layout="columns" startAt="small" vAlign="top" messages={this.dateInputErrors()} > <DateInput label={I18n.t('Start Date')} previousLabel={I18n.t('Previous Month')} nextLabel={I18n.t('Next Month')} onDateChange={this.setSelectedFrom} /> <DateInput label={I18n.t('End Date')} previousLabel={I18n.t('Previous Month')} nextLabel={I18n.t('Next Month')} onDateChange={this.setSelectedTo} /> </FormFieldGroup> <div style={{margin: "1.85rem 0 0 0"}}> <Button onClick={this.handleSubmit} type="submit" variant="primary" disabled={this.hasDateInputErrors()} > {I18n.t('Filter')} </Button> </div> </FormFieldGroup> </Container> ); } } const mapStateToProps = state => ( { fetchHistoryStatus: state.history.fetchHistoryStatus || '', assignments: { fetchStatus: state.searchForm.records.assignments.fetchStatus || '', items: state.searchForm.records.assignments.items || [], nextPage: state.searchForm.records.assignments.nextPage || '' }, graders: { fetchStatus: state.searchForm.records.graders.fetchStatus || '', items: state.searchForm.records.graders.items || [], nextPage: state.searchForm.records.graders.nextPage || '' }, students: { fetchStatus: state.searchForm.records.students.fetchStatus || '', items: state.searchForm.records.students.items || [], nextPage: state.searchForm.records.students.nextPage || '' } } ); const mapDispatchToProps = dispatch => ( { getGradebookHistory: (input) => { dispatch(SearchFormActions.getGradebookHistory(input)); }, getSearchOptions: (recordType, searchTerm) => { dispatch(SearchFormActions.getSearchOptions(recordType, searchTerm)); }, getSearchOptionsNextPage: (recordType, url) => { dispatch(SearchFormActions.getSearchOptionsNextPage(recordType, url)); }, clearSearchOptions: (recordType) => { dispatch(SearchFormActions.clearSearchOptions(recordType)); } } ); export default connect(mapStateToProps, mapDispatchToProps)(SearchFormComponent); export { SearchFormComponent };
examples/with-apollo-and-redux-saga/components/PostVoteDown.js
BlancheXu/test
import React from 'react' import { graphql } from 'react-apollo' import gql from 'graphql-tag' import PostVoteButton from './PostVoteButton' function PostVoteDown ({ downvote, votes, id }) { return ( <PostVoteButton id={id} votes={votes} className='downvote' onClickHandler={() => downvote(id, votes - 1)} /> ) } const downvotePost = gql` mutation updatePost($id: ID!, $votes: Int) { updatePost(id: $id, votes: $votes) { id __typename votes } } ` export default graphql(downvotePost, { props: ({ ownProps, mutate }) => ({ downvote: (id, votes) => mutate({ variables: { id, votes }, optimisticResponse: { __typename: 'Mutation', updatePost: { __typename: 'Post', id: ownProps.id, votes: ownProps.votes - 1 } } }) }) })(PostVoteDown)
packages/react-devtools-shared/src/devtools/views/Components/HocBadges.js
rricard/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import { ElementTypeForwardRef, ElementTypeMemo, } from 'react-devtools-shared/src/types'; import styles from './HocBadges.css'; import type {Element} from './types'; type Props = {| element: Element, |}; export default function HocBadges({element}: Props) { const {hocDisplayNames, type} = ((element: any): Element); let typeBadge = null; if (type === ElementTypeMemo) { typeBadge = 'Memo'; } else if (type === ElementTypeForwardRef) { typeBadge = 'ForwardRef'; } if (hocDisplayNames === null && typeBadge === null) { return null; } return ( <div className={styles.HocBadges}> {typeBadge !== null && <div className={styles.Badge}>{typeBadge}</div>} {hocDisplayNames !== null && hocDisplayNames.map(hocDisplayName => ( <div key={hocDisplayName} className={styles.Badge}> {hocDisplayName} </div> ))} </div> ); }
src/svg-icons/image/filter-tilt-shift.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterTiltShift = (props) => ( <SvgIcon {...props}> <path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/> </SvgIcon> ); ImageFilterTiltShift = pure(ImageFilterTiltShift); ImageFilterTiltShift.displayName = 'ImageFilterTiltShift'; ImageFilterTiltShift.muiName = 'SvgIcon'; export default ImageFilterTiltShift;
exercise-07/src/components/PokemonCard.js
learnapollo/pokedex-react
import React from 'react' import { propType } from 'graphql-anywhere' import gql from 'graphql-tag' import { graphql } from 'react-apollo' import styled from 'styled-components' const Button = styled.div` background-color: ${props => props.save ? '#2BC3A1' : ''}; color: ${props => props.save ? 'white' : props.delete ? '#ba2626' : '#A3A3A3'}; height: 48px; line-height: 1; font-size: 18px; padding: 15px 30px; cursor: pointer; font-weight: 300; border-radius: 4px ` const Card = styled.div` background-color: white; box-shadow: 0 1px 11px 0 rgba(0, 0, 0, 0.2); border-radius: 3px; padding: 20px; ` class PokemonCard extends React.Component { static fragments = { pokemon: gql` fragment PokemonCardPokemon on Pokemon { id url name } ` } static propTypes = { pokemon: propType(PokemonCard.fragments.pokemon).isRequired, handleCancel: React.PropTypes.func.isRequired, afterChange: React.PropTypes.func.isRequired, updatePokemon: React.PropTypes.func.isRequired, deletePokemon: React.PropTypes.func.isRequired, } state = { name: this.props.pokemon.name, url: this.props.pokemon.url, } render () { return ( <div className='w-100 pa4 flex justify-center'> <Card style={{ maxWidth: 400 }}> <input className='w-100 pa3 mv2' value={this.state.name} placeholder='Name' onChange={(e) => this.setState({name: e.target.value})} /> <input className='w-100 pa3 mv2' value={this.state.url} placeholder='Image Url' onChange={(e) => this.setState({url: e.target.value})} /> {this.state.url && <img src={this.state.url} role='presentation' className='w-100 mv3 pa4' /> } <div className='flex justify-between'> <Button delete onClick={this.handleDelete}>Delete</Button> <Button onClick={this.props.handleCancel}>Cancel</Button> {this.canUpdate() ? <Button save onClick={this.handleUpdate}>Update</Button> : <Button disabled>Update</Button> } </div> </Card> </div> ) } canUpdate = () => { return this.state.name && this.state.url && (this.props.pokemon.name !== this.state.name || this.props.pokemon.url !== this.state.url) } handleUpdate = () => { this.props.updatePokemon({variables: { id: this.props.pokemon.id, name: this.state.name, url: this.state.url }}) .then(this.props.afterChange) } handleDelete = () => { this.props.deletePokemon({variables: { id: this.props.pokemon.id }}) .then(this.props.afterChange) } } const updatePokemon = gql` mutation updatePokemon($id: ID!, $name: String!, $url: String!) { updatePokemon(id: $id, name: $name, url: $url) { id ... PokemonCardPokemon } } ${PokemonCard.fragments.pokemon} ` const deletePokemon = gql` mutation deletePokemon($id: ID!) { deletePokemon(id: $id) { id } } ` const PokemonCardWithMutations = graphql(deletePokemon, {name : 'deletePokemon'})( graphql(updatePokemon, {name: 'updatePokemon'})(PokemonCard) ) export default PokemonCardWithMutations
examples/basic/src/components/RandomButton/RandomButton.js
sapegin/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import sample from 'lodash/sample'; import './RandomButton.css'; /** * Button that changes label on every click. */ // eslint-disable-next-line import/prefer-default-export export class RandomButton extends Component { static propTypes = { /** * List of possible labels. */ variants: PropTypes.array.isRequired, }; constructor(props) { super(); this.state = { label: sample(props.variants), }; } handleClick = () => { this.setState({ label: sample(this.props.variants), }); }; render() { return ( <button className="random-button" onClick={this.handleClick}> {this.state.label} </button> ); } }
packages/core/admin/admin/src/content-manager/components/DynamicComponentCard/index.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import Wrapper from './Wrapper'; const DynamicComponentCard = ({ children, componentUid, friendlyName, icon, onClick }) => { return ( <Wrapper onClick={e => { e.preventDefault(); e.stopPropagation(); onClick(componentUid); }} > <button className="component-icon" type="button"> <FontAwesomeIcon icon={icon} /> </button> <div className="component-uid"> <span>{friendlyName}</span> </div> {children} </Wrapper> ); }; DynamicComponentCard.defaultProps = { children: null, friendlyName: '', onClick: () => {}, icon: 'smile', }; DynamicComponentCard.propTypes = { children: PropTypes.node, componentUid: PropTypes.string.isRequired, friendlyName: PropTypes.string, icon: PropTypes.string, onClick: PropTypes.func, }; export default DynamicComponentCard;
frontend/src/Settings/Quality/Definition/QualityDefinition.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import ReactSlider from 'react-slider'; import NumberInput from 'Components/Form/NumberInput'; import TextInput from 'Components/Form/TextInput'; import Label from 'Components/Label'; import Popover from 'Components/Tooltip/Popover'; import { kinds, tooltipPositions } from 'Helpers/Props'; import formatBytes from 'Utilities/Number/formatBytes'; import roundNumber from 'Utilities/Number/roundNumber'; import translate from 'Utilities/String/translate'; import QualityDefinitionLimits from './QualityDefinitionLimits'; import styles from './QualityDefinition.css'; const MIN = 0; const MAX = 400; const MIN_DISTANCE = 1; const slider = { min: MIN, max: roundNumber(Math.pow(MAX, 1 / 1.1)), step: 0.1 }; function getValue(inputValue) { if (inputValue < MIN) { return MIN; } if (inputValue > MAX) { return MAX; } return roundNumber(inputValue); } function getSliderValue(value, defaultValue) { const sliderValue = value ? Math.pow(value, 1 / 1.1) : defaultValue; return roundNumber(sliderValue); } class QualityDefinition extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { sliderMinSize: getSliderValue(props.minSize, slider.min), sliderMaxSize: getSliderValue(props.maxSize, slider.max), sliderPreferredSize: getSliderValue(props.preferredSize, (slider.max - 3)) }; } // // Listeners onSliderChange = ([sliderMinSize, sliderPreferredSize, sliderMaxSize]) => { this.setState({ sliderMinSize, sliderMaxSize, sliderPreferredSize }); this.props.onSizeChange({ minSize: roundNumber(Math.pow(sliderMinSize, 1.1)), preferredSize: sliderPreferredSize === (slider.max - 3) ? null : roundNumber(Math.pow(sliderPreferredSize, 1.1)), maxSize: sliderMaxSize === slider.max ? null : roundNumber(Math.pow(sliderMaxSize, 1.1)) }); } onAfterSliderChange = () => { const { minSize, maxSize, preferredSize } = this.props; this.setState({ sliderMiSize: getSliderValue(minSize, slider.min), sliderMaxSize: getSliderValue(maxSize, slider.max), sliderPreferredSize: getSliderValue(preferredSize, (slider.max - 3)) // fix }); } onMinSizeChange = ({ value }) => { const minSize = getValue(value); this.setState({ sliderMinSize: getSliderValue(minSize, slider.min) }); this.props.onSizeChange({ minSize, maxSize: this.props.maxSize, preferredSize: this.props.preferredSize }); } onPreferredSizeChange = ({ value }) => { const preferredSize = value === (MAX - 3) ? null : getValue(value); this.setState({ sliderPreferredSize: getSliderValue(preferredSize, slider.preferred) }); this.props.onSizeChange({ minSize: this.props.minSize, maxSize: this.props.maxSize, preferredSize }); } onMaxSizeChange = ({ value }) => { const maxSize = value === MAX ? null : getValue(value); this.setState({ sliderMaxSize: getSliderValue(maxSize, slider.max) }); this.props.onSizeChange({ minSize: this.props.minSize, maxSize, preferredSize: this.props.preferredSize }); } // // Render render() { const { id, quality, title, minSize, maxSize, preferredSize, advancedSettings, onTitleChange } = this.props; const { sliderMinSize, sliderMaxSize, sliderPreferredSize } = this.state; const minBytes = minSize * 1024 * 1024; const minSixty = `${formatBytes(minBytes * 60)}/h`; const preferredBytes = preferredSize * 1024 * 1024; const preferredSixty = preferredBytes ? `${formatBytes(preferredBytes * 60)}/h` : translate('Unlimited'); const maxBytes = maxSize && maxSize * 1024 * 1024; const maxSixty = maxBytes ? `${formatBytes(maxBytes * 60)}/h` : translate('Unlimited'); return ( <div className={styles.qualityDefinition}> <div className={styles.quality}> {quality.name} </div> <div className={styles.title}> <TextInput name={`${id}.${title}`} value={title} onChange={onTitleChange} /> </div> <div className={styles.sizeLimit}> <ReactSlider min={slider.min} max={slider.max} step={slider.step} minDistance={MIN_DISTANCE * 3} value={[sliderMinSize, sliderPreferredSize, sliderMaxSize]} withTracks={true} allowCross={false} snapDragDisabled={true} className={styles.slider} trackClassName={styles.bar} thumbClassName={styles.handle} onChange={this.onSliderChange} onAfterChange={this.onAfterSliderChange} /> <div className={styles.sizes}> <div> <Popover anchor={ <Label kind={kinds.INFO}>{minSixty}</Label> } title={translate('MinimumLimits')} body={ <QualityDefinitionLimits bytes={minBytes} message={translate('NoMinimumForAnyRuntime')} /> } position={tooltipPositions.BOTTOM} /> </div> <div> <Popover anchor={ <Label kind={kinds.SUCCESS}>{preferredSixty}</Label> } title={translate('PreferredSize')} body={ <QualityDefinitionLimits bytes={preferredBytes} message={translate('NoLimitForAnyRuntime')} /> } position={tooltipPositions.BOTTOM} /> </div> <div> <Popover anchor={ <Label kind={kinds.WARNING}>{maxSixty}</Label> } title={translate('MaximumLimits')} body={ <QualityDefinitionLimits bytes={maxBytes} message={translate('NoLimitForAnyRuntime')} /> } position={tooltipPositions.BOTTOM} /> </div> </div> </div> { advancedSettings && <div className={styles.megabytesPerMinute}> <div> {translate('Min')} <NumberInput className={styles.sizeInput} name={`${id}.min`} value={minSize || MIN} min={MIN} max={preferredSize ? preferredSize - MIN_DISTANCE : MAX - MIN_DISTANCE} step={0.1} isFloat={true} onChange={this.onMinSizeChange} /> </div> <div> {translate('Preferred')} <NumberInput className={styles.sizeInput} name={`${id}.min`} value={preferredSize || MAX - MIN_DISTANCE} min={MIN} max={maxSize ? maxSize - MIN_DISTANCE : MAX - MIN_DISTANCE} step={0.1} isFloat={true} onChange={this.onPreferredSizeChange} /> </div> <div> {translate('Max')} <NumberInput className={styles.sizeInput} name={`${id}.max`} value={maxSize || MAX} min={minSize + MIN_DISTANCE} max={MAX} step={0.1} isFloat={true} onChange={this.onMaxSizeChange} /> </div> </div> } </div> ); } } QualityDefinition.propTypes = { id: PropTypes.number.isRequired, quality: PropTypes.object.isRequired, title: PropTypes.string.isRequired, minSize: PropTypes.number, maxSize: PropTypes.number, preferredSize: PropTypes.number, advancedSettings: PropTypes.bool.isRequired, onTitleChange: PropTypes.func.isRequired, onSizeChange: PropTypes.func.isRequired }; export default QualityDefinition;
src/pages/resume.js
evanfrawley/evanfrawley.github.io
import React from 'react' const Resume = () => ( <div> <p>My resume can be found <a href="/Frawley_Resume.pdf" target="_blank">here</a>.</p> </div> ) export default Resume
src/svg-icons/image/crop-16-9.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop169 = (props) => ( <SvgIcon {...props}> <path d="M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z"/> </SvgIcon> ); ImageCrop169 = pure(ImageCrop169); ImageCrop169.displayName = 'ImageCrop169'; export default ImageCrop169;
docs/app/components/preview/index.js
VACO-GitHub/vaco-components-library
/*eslint-disable no-eval*/ import React from 'react'; import ReactDOM from 'react-dom'; import { ThemeProvider } from 'react-css-themr'; import { transform } from 'babel-standalone'; import * as ReactToolbox from 'react-toolbox'; import theme from '../../theme/theme.js'; import style from './style'; const ERROR_TIMEOUT = 500; const Preview = React.createClass({ propTypes: { className: React.PropTypes.string, code: React.PropTypes.string.isRequired, scope: React.PropTypes.object }, getDefaultProps () { return { className: '', scope: { React, ...ReactToolbox } }; }, getInitialState () { return { error: null }; }, componentDidMount () { this.executeCode(); }, componentDidUpdate (prevProps) { clearTimeout(this.timeoutID); if (this.props.code !== prevProps.code) { this.executeCode(); } }, setTimeout () { clearTimeout(this.timeoutID); this.timeoutID = setTimeout(...arguments); }, compileCode () { const code = ` (function (${Object.keys(this.props.scope).join(', ')}, mountNode) { ${this.props.code} });`; return transform(code, { presets: ['es2015', 'stage-0', 'react'] }).code; }, buildScope (mountNode) { return Object.keys(this.props.scope).map((key) => { return this.props.scope[key]; }).concat(mountNode); }, executeCode () { const mountNode = this.refs.mount; const scope = this.buildScope(mountNode); try { ReactDOM.unmountComponentAtNode(mountNode); } catch (e) { console.error(e); } try { ReactDOM.render( <ThemeProvider theme={theme}> {eval(this.compileCode())(...scope)} </ThemeProvider> , mountNode); if (this.state.error) { this.setState({error: null}); } } catch (err) { this.setTimeout(() => { this.setState({error: err.toString()}); }, ERROR_TIMEOUT); } }, render () { let className = style.preview; if (this.props.className) className += ` ${this.props.className}`; return ( <div className={className}> {this.state.error !== null ? <span className={style.error}>{this.state.error}</span> : null} <div ref="mount" className={style.content} /> </div> ); } }); export default Preview;
src/svg-icons/action/settings-input-composite.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputComposite = (props) => ( <SvgIcon {...props}> <path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/> </SvgIcon> ); ActionSettingsInputComposite = pure(ActionSettingsInputComposite); ActionSettingsInputComposite.displayName = 'ActionSettingsInputComposite'; ActionSettingsInputComposite.muiName = 'SvgIcon'; export default ActionSettingsInputComposite;
src/svg-icons/action/view-week.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewWeek = (props) => ( <SvgIcon {...props}> <path d="M6 5H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm14 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm-7 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z"/> </SvgIcon> ); ActionViewWeek = pure(ActionViewWeek); ActionViewWeek.displayName = 'ActionViewWeek'; ActionViewWeek.muiName = 'SvgIcon'; export default ActionViewWeek;
dashboard-ui/app/components/queue/ACL.js
CloudBoost/cloudboost
import React from 'react'; import PropTypes from 'prop-types'; import { Modal, Button } from 'react-bootstrap'; import { updateQueue } from '../../actions'; import { connect } from 'react-redux'; import ACLRows from './aclRows.js'; export class ACL extends React.Component { static propTypes = { selectedQueue: PropTypes.any, updateQueue: PropTypes.any, closeACLModal: PropTypes.any, showACLModal: PropTypes.any } constructor () { super(); this.state = { aclList: [] }; } componentWillMount () { this.generaliseACL(this.props.selectedQueue); } generaliseACL (props) { let users = {}; let roles = {}; for (let k in props.ACL.document.read.allow.user) { if (!users[props.ACL.document.read.allow.user[k]]) users[props.ACL.document.read.allow.user[k]] = {}; users[props.ACL.document.read.allow.user[k]].read = true; } for (let k in props.ACL.document.read.deny.user) { if (!users[props.ACL.document.read.deny.user[k]]) users[props.ACL.document.read.deny.user[k]] = {}; users[props.ACL.document.read.deny.user[k]].read = false; } for (let k in props.ACL.document.write.allow.user) { if (!users[props.ACL.document.write.allow.user[k]]) users[props.ACL.document.write.allow.user[k]] = {}; users[props.ACL.document.write.allow.user[k]].write = true; } for (let k in props.ACL.document.write.deny.user) { if (!users[props.ACL.document.write.deny.user[k]]) users[props.ACL.document.write.deny.user[k]] = {}; users[props.ACL.document.write.deny.user[k]].write = false; } for (let k in props.ACL.document.read.allow.role) { if (!roles[props.ACL.document.read.allow.role[k]]) roles[props.ACL.document.read.allow.role[k]] = {}; roles[props.ACL.document.read.allow.role[k]].read = true; } for (let k in props.ACL.document.read.deny.role) { if (!roles[props.ACL.document.read.deny.role[k]]) roles[props.ACL.document.read.deny.role[k]] = {}; roles[props.ACL.document.read.deny.role[k]].read = false; } for (let k in props.ACL.document.write.allow.role) { if (!roles[props.ACL.document.write.allow.role[k]]) roles[props.ACL.document.write.allow.role[k]] = {}; roles[props.ACL.document.write.allow.role[k]].write = true; } for (let k in props.ACL.document.write.deny.role) { if (!roles[props.ACL.document.write.deny.role[k]]) roles[props.ACL.document.write.deny.role[k]] = {}; roles[props.ACL.document.write.deny.role[k]].write = false; } let usersList = []; let rolesList = []; usersList = Object.keys(users).map((x) => { return { id: x, data: users[x], type: 'user' }; }); rolesList = Object.keys(roles).map((x) => { return { id: x, data: roles[x], type: 'role' }; }); this.state.aclList = [...usersList, ...rolesList]; this.setState(this.state); } removeAcl = (id) => { this.state.aclList = this.state.aclList.filter(x => x.id !== id); this.setState(this.state); } updateAclData = (data, id) => { this.state.aclList = this.state.aclList.map((x) => { if (x.id === id) { x.data = data; } return x; }); this.setState(this.state); } addAcl = (obj) => { this.state.aclList.push(obj); this.setState(this.state); } saveAcl = () => { let AClObj = new CB.ACL(); for (var k in this.state.aclList) { if (this.state.aclList[k].type === 'user' && this.state.aclList[k].id !== 'all') { let typeRead = this.state.aclList[k].data.read || false; let typeWrite = this.state.aclList[k].data.write || false; AClObj.setUserReadAccess(this.state.aclList[k].id, typeRead); AClObj.setUserWriteAccess(this.state.aclList[k].id, typeWrite); } if (this.state.aclList[k].type === 'role') { let typeRead = this.state.aclList[k].data.read || false; let typeWrite = this.state.aclList[k].data.write || false; AClObj.setRoleReadAccess(this.state.aclList[k].id, typeRead); AClObj.setRoleWriteAccess(this.state.aclList[k].id, typeWrite); } if (this.state.aclList[k].id === 'all') { AClObj.setPublicReadAccess(this.state.aclList[k].data.read); AClObj.setPublicWriteAccess(this.state.aclList[k].data.write); } } this.props.selectedQueue.ACL = AClObj; this.props.updateQueue(this.props.selectedQueue); this.close(); } close = () => { this.props.closeACLModal(); }; render () { return ( <Modal show={this.props.showACLModal} onHide={this.close} dialogClassName='custom-modal'> <Modal.Header className='modal-header-style'> <Modal.Title> <span className='modal-title-style'> Access Control List (ACL) </span> <i className='fa fa-exchange modal-icon-style pull-right' /> <div className='modal-title-inner-text'> ACL's helps you to secure your app </div> </Modal.Title> </Modal.Header> <Modal.Body style={{ padding: 15 }}> <ACLRows aclList={this.state.aclList} removeAcl={this.removeAcl} addAcl={this.addAcl} updateAclData={this.updateAclData} /> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>Cancel</Button> <Button bsStyle='primary' onClick={this.saveAcl}>Save</Button> </Modal.Footer> </Modal> ); } } const mapStateToProps = (state) => { return {}; }; const mapDispatchToProps = (dispatch) => { return { updateQueue: (selectedQueue) => dispatch(updateQueue(selectedQueue)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(ACL);
react/features/prejoin/components/DropdownButton.js
gpolitis/jitsi-meet
// @flow import { withStyles } from '@material-ui/styles'; import React from 'react'; import { Icon } from '../../base/icons'; type Props = { /** * The css classes generated from theme. */ classes: Object, /** * Attribute used in automated testing. */ dataTestId: string, /** * The button's icon. */ icon: HTMLElement, /** * The button's label. */ label: string, /** * Function to be called when button is clicked. */ onButtonClick: Function, /** * Function to be called on key pressed. */ onKeyPressed: Function, /** * Used for translation. */ t: Function }; /** * Creates the styles for the component. * * @param {Object} theme - The current UI theme. * * @returns {Object} */ const styles = theme => { return { prejoinPreviewDropdownBtn: { alignItems: 'center', color: '#1C2025', cursor: 'pointer', display: 'flex', height: 40, fontSize: 15, lineHeight: '24px', padding: '0 16px', backgroundColor: theme.palette.field02, '&:hover': { backgroundColor: theme.palette.field02Hover } }, prejoinPreviewDropdownIcon: { display: 'inline-block', marginRight: 16, '& > svg': { fill: '#1C2025' } } }; }; /** * Buttons used for pre meeting actions. * * @returns {ReactElement} */ const DropdownButton = ({ classes, dataTestId, icon, onButtonClick, onKeyPressed, label }: Props) => ( <div className = { classes.prejoinPreviewDropdownBtn } data-testid = { dataTestId } onClick = { onButtonClick } onKeyPress = { onKeyPressed } role = 'button' tabIndex = { 0 }> <Icon className = { classes.prejoinPreviewDropdownIcon } size = { 24 } src = { icon } /> {label} </div> ); export default withStyles(styles)(DropdownButton);
src/svg-icons/image/brightness-2.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness2 = (props) => ( <SvgIcon {...props}> <path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/> </SvgIcon> ); ImageBrightness2 = pure(ImageBrightness2); ImageBrightness2.displayName = 'ImageBrightness2'; ImageBrightness2.muiName = 'SvgIcon'; export default ImageBrightness2;
src/components/quiz/QuizPage.js
zulis/react-quiz-demo
import React from 'react'; import Question from './Question'; import * as ApiCtrl from '../../controllers/ApiController'; class QuizPage extends React.Component { constructor(props) { super(props); this.state = { quiz: {}, userAnswers: [], step: 0 }; this.setAnswer = this.setAnswer.bind(this); } componentDidMount() { ApiCtrl.getById(this.props.routeParams.id) .then(response => { this.setState({ quiz: response }); }); } setAnswer(e) { var answerIdx = e.target.id; var isCorrect = this.state.quiz.questions[this.state.step].answers[answerIdx].correct === "true"; var userAnswers = this.state.userAnswers; userAnswers[this.state.step] = isCorrect; this.setState({ userAnswers, step: (this.state.step + 1) }); } getScore() { return this.state.userAnswers.filter(entry => { return entry === true; }).length; } renderResult() { return ( <div> <h2>Results</h2> <div> <div className="alert">Correct <strong>{this.getScore()}</strong> of total <strong>{this.state.quiz.questions.length}</strong> questions</div> </div> <div> <h2>Your answers</h2> {this.state.quiz.questions.map((question, idx) => { let items = []; if (this.state.userAnswers[idx]) { items.push( <div className="alert alert-success"><span>&#10004; {question.question}</span></div> ); } else { items.push( <div className="alert alert-danger"><span>&#10008; {question.question}</span></div> ); } return items; })} </div> </div> ); } render() { if (!this.state.quiz._id) { return <div></div> } let showResult = this.state.step === this.state.quiz.questions.length; return ( <div> <h1>{this.state.quiz.title}</h1> {( showResult ? (<div>{this.renderResult()}</div>) : (<Question question={this.state.quiz.questions[this.state.step]} setAnswer={this.setAnswer} />) )} </div> ); } } export default QuizPage;
src/fields/DatePicker/index.js
cantonjs/re-admin
import React from 'react'; import PropTypes from 'prop-types'; import { DatePicker } from 'components/Form'; import field from 'hocs/field'; import moment from 'moment'; import { isString, isObject, isFunction } from 'utils/fp'; import renderDate from 'utils/renderDate'; const buildInDefaultProps = { inputFilter(val) { if (!val) return; if (isObject(val)) return val; if (isString(val)) return moment(val); }, outputFilter(val) { if (!val) return; if (isFunction(val.toISOString)) return val.toISOString(); if (isString(val)) return val; }, }; function DatePickerField(props) { return ( <DatePicker defaultValue={undefined} {...props} {...buildInDefaultProps} /> ); } /* eslint-disable react/prop-types */ DatePickerField.renderTable = function renderTable( { format, dateFormat }, { value } ) { return <span>{renderDate(value, format, dateFormat)}</span>; }; DatePickerField.propTypes = { format: PropTypes.string, dateFormat: PropTypes.string, }; DatePickerField.defaultProps = { format: 'date', }; export default field(DatePickerField);
src/components/Navbar.js
emjayoh/nsii
import React from 'react' import { Link } from 'gatsby' import github from '../img/github-icon.svg' import logo from '../img/logo.svg' const Navbar = class extends React.Component { componentDidMount() { // Get all "navbar-burger" elements const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach( el => { el.addEventListener('click', () => { // Get the target from the "data-target" attribute const target = el.dataset.target; const $target = document.getElementById(target); // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } } render() { return ( <nav className="navbar is-transparent" role="navigation" aria-label="main-navigation"> <div className="container"> <div className="navbar-brand"> <Link to="/" className="navbar-item" title="Logo"> <img src={logo} alt="Kaldi" style={{ width: '88px' }} /> </Link> {/* Hamburger menu */} <div className="navbar-burger burger" data-target="navMenu"> <span></span> <span></span> <span></span> </div> </div> <div id="navMenu" className="navbar-menu"> <div className="navbar-start has-text-centered"> <Link className="navbar-item" to="/about"> About </Link> <Link className="navbar-item" to="/products"> Products </Link> <Link className="navbar-item" to="/contact"> Contact </Link> <Link className="navbar-item" to="/contact/examples"> Form Examples </Link> </div> <div className="navbar-end has-text-centered"> <a className="navbar-item" href="https://github.com/AustinGreen/gatsby-netlify-cms-boilerplate" target="_blank" rel="noopener noreferrer" > <span className="icon"> <img src={github} alt="Github" /> </span> </a> </div> </div> </div> </nav> )} } export default Navbar
examples/official-storybook/stories/addon-queryparams.stories.js
kadirahq/react-storybook
import { document } from 'global'; import React from 'react'; export default { title: 'Addons/QueryParams', parameters: { query: { mock: true, }, }, }; export const MockIsTrue = () => ( <div>This story should have an extra url query param: {document.location.search}</div> ); MockIsTrue.storyName = 'mock is true'; export const MockIs4 = () => ( <div>This story should have an extra url query param: {document.location.search}</div> ); MockIs4.storyName = 'mock is 4'; MockIs4.parameters = { query: { mock: 4 } };
src/components/Weui/mediabox/mediabox_desc.js
ynu/ecard-wxe
/** * Created by n7best */ import React from 'react'; import classNames from 'classnames'; export default class MediaBoxDescription extends React.Component { render() { const {children, className, ...others} = this.props; const cls = classNames({ weui_media_desc: true }, className); return ( <p className={cls} {...others}>{children}</p> ); } };
packages/material-ui-icons/src/WbIncandescent.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let WbIncandescent = props => <SvgIcon {...props}> <path d="M3.55 18.54l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8zM11 22.45h2V19.5h-2v2.95zM4 10.5H1v2h3v-2zm11-4.19V1.5H9v4.81C7.21 7.35 6 9.28 6 11.5c0 3.31 2.69 6 6 6s6-2.69 6-6c0-2.22-1.21-4.15-3-5.19zm5 4.19v2h3v-2h-3zm-2.76 7.66l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4z" /> </SvgIcon>; WbIncandescent = pure(WbIncandescent); WbIncandescent.muiName = 'SvgIcon'; export default WbIncandescent;
stories/Emoji/CustomEmojiEditor/index.js
dagopert/draft-js-plugins
import React, { Component } from 'react'; import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor'; import createEmojiPlugin from 'draft-js-emoji-plugin'; import editorStyles from './editorStyles.css'; const emojiPlugin = createEmojiPlugin({ useNativeArt: true }); const { EmojiSuggestions, EmojiSelect } = emojiPlugin; const plugins = [emojiPlugin]; const text = `Cool, we can have all sorts of Emojis here. 🙌 🌿☃️🎉🙈 aaaand maybe a few more here 🐲☀️🗻 Quite fun!`; export default class CustomEmojiEditor extends Component { state = { editorState: createEditorStateWithText(text), }; 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; }} /> <EmojiSuggestions /> </div> <div className={editorStyles.options}> <EmojiSelect /> </div> </div> ); } }
src/main/internal/adaption/react/Boundary.js
mcjazzyfunky/js-surface
// external imports import React from 'react' // --- Boundary ----------------------------------------------------- class Boundary extends React.Component { componentDidCatch(error, info) { if (this.props.fallback) { this.props.fallback(error, info) } } render() { return this.props.children } } Boundary.displayName = 'Boundary (inner)' Boundary.getDerivedStateFromError = () => { } // --- exports ------------------------------------------------------ export default Boundary
src/app.js
VahanAper/checkin
import React, { Component } from 'react'; import { geolocated } from 'react-geolocated'; import { Header, CheckinMap, CheckinButton, CheckinList, Modal, CheckinReduxForm as CheckinForm } from './components'; class App extends Component { renderGeolocation() { const { coords } = this.props; if (!this.props.coords) { return ( <div className="col-md-8 col-md-offset-2 bg-warning text-warning no-geolocation"> Please allow geolocation. </div> ); } return <CheckinMap zoom={17} coords={coords} />; } render() { return ( <div className="container"> <Header title="Check-in Yourself" /> <div className="row"> {this.renderGeolocation()} </div> <CheckinButton target="#checkin-modal" title="Check-in Now" coords={this.props.coords} /> <CheckinList /> <Modal header="Please enter your name" id="checkin-modal"> <CheckinForm label="Name" submitText="Checkin" cancelText="Cancel" coords={this.props.coords} /> </Modal> </div> ); } } export default geolocated({ positionOptions: { enableHighAccuracy: false, }, userDecisionTimeout: 5000 })(App);
src/dataTypes/Null.js
mrose/react-dump
import React from 'react'; import { Row, Table } from '../format'; export const Null = ( props ) => { const opts = props.opts || { expand:true , format:'html' , label:'Null' } let { label, expand } = opts return ( <Table className='reactdump reactdump-Null' expand={expand}> <Row className='reactdump-label reactdump-Null' label={label} expand={expand} cols='1'> {obj} </Row> </Table> ) };
gitweb/public/js/routes.js
alanctgardner/gitweb
import React from 'react'; import Router from 'react-router'; var { Route, RouteHandler } = Router; import { GithubPanel } from 'components/github-panel'; import { RepoPanel } from 'components/repo-panel'; import authStore from 'stores/auth-store'; var TopNav = React.createClass({ renderLoggedOut() { return ( <li> <a href='/auth/login'>Login</a> </li> ); }, renderLoggedIn() { return ( <li> <a href='/auth/logout'>logout</a> </li> ); }, render() { var contents = this.props.token ? this.renderLoggedIn() : this.renderLoggedOut(); return ( <div className='navbar navbar-default navbar-static-top top-nav'> <ul className='nav navbar-nav pull-right'> {contents} </ul> </div> ); } }); var App = React.createClass({ getInitialState() { let token = authStore.token() return { token } }, render() { return ( <div className='app'> <div className='app-header'> <TopNav token={this.state.token} /> </div> <RouteHandler /> </div> ); } }); var Authenticated = React.createClass({ statics: { willTransitionTo(transition, params, query) { var token = authStore.token() if (!token) { return transition.redirect('login') } } }, render() { return ( <div className='app-body'> <GithubPanel token={authStore.token()}> <RouteHandler /> </GithubPanel> </div> ); } }); var Home = React.createClass({ render() { return (<div>home</div>) } }); var Login = React.createClass({ render() { return ( <h1>Must Log In</h1> ); } }); export var routes = ( <Route handler={App}> <Route handler={Authenticated}> <Route path='/' handler={Home} /> <Route path='/repo/:owner/:name' name='repo-view' handler={RepoPanel} /> </Route> <Route handler={Login} name='login' path='/login' /> </Route> );
demo/app/screens/login/LoginScreen.js
braveliuchina/pig-react-native
import React, { Component } from 'react'; import { ToolbarAndroid, AppRegistry, StyleSheet, Text, ScrollView, View, Image, TextInput, TouchableOpacity } from 'react-native'; import Cookie from 'react-native-cookie'; import {Images, LoginStyles} from '../../resource/'; import {EditView, LoginButton, NetUtil, LoginSuccess} from '../../components/'; export default class LoginScreen extends Component { constructor(props) { super(props); this.userName = ""; this.password = ""; } render() { return ( <View style={LoginStyles.loginview}> <View style={LoginStyles.topimg}> <Image source={Images.ic_login} style={LoginStyles.img}/> </View> <View style={LoginStyles.toptext}> <Text>最专业的养猪APP</Text> </View> <View style={LoginStyles.user}> <EditView name='手机号' onChangeText={(text) => { this.userName = text; }}/> <EditView name='请输入登陆密码' onChangeText={(text) => { this.password = text; }}/> <View style={LoginStyles.btnView}> <LoginButton name='登录' onPressCallback={this.onPressCallback} style={LoginStyles.btn}/> </View> </View> </View> ) } onPressCallback = () => { //let formData = new FormData(); var req = { 'platform':'telephone', 'telephone': this.userName, 'pwd': this.password } // alert(JSON.stringify(req)) //formData.append('req', req) // formData.append('platform','local') // formData.append('phoneNum': this.userName) // //formData.append("loginName",this.userName); // formData.append("pwd",this.password); let url = "http://syhlife.com:8020/pig/login"; NetUtil.postJson(url,JSON.stringify(req), false, (responseText) => { alert(responseText); response = JSON.parse(responseText) if(response['retcode'] == '0'){ this.onLoginSuccess(response); }else{ this.onLoginFailed(response); } }) }; _navigateToScreen(screen) { //Toast.show(screen) const {navigate} = this.props.navigation; navigate(screen); } //跳转到第二个页面去 onLoginSuccess(response){ Cookie.set('http://syhlife.com/', 'token',response['token'], { path: '/', expires: new Date('Thu, 1 Jan 2030 00:00:00 GMT'), domain: 'syhlife.com' }).then(() => console.log('success')); Cookie.set('http://syhlife.com/', 'usertype',response['userType'], { path: '/', expires: new Date('Thu, 1 Jan 2030 00:00:00 GMT'), domain: 'syhlife.com' }).then(() => console.log('success')); Cookie.set('http://syhlife.com/', 'userid',response['user']['id'], { path: '/', expires: new Date('Thu, 1 Jan 2030 00:00:00 GMT'), domain: 'syhlife.com' }).then(() => console.log('success')); // var cookie = 'user_session='+ response['user']['id'] +'; path=/; token='+ response['token'] + '; expires=Thu, 1 Jan 2030 00:00:00 -0000; secure; HttpOnly'; // CookieManager.setFromResponse( // 'http://syhlife.com/', // cookie // ) // .then((res) => { // // `res` will be true or false depending on success. // console.log('CookieManager.setFromResponse =>', res); // }); this._navigateToScreen('Home') } //不跳转页面 onLoginFailed(){ alert(response['retdesc']); this._navigateToScreen('Home') } }
src/js/components/Carousel.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Box from './Box'; import Tiles from './Tiles'; import Tile from './Tile'; import Button from './Button'; import PreviousIcon from './icons/base/Previous'; import NextIcon from './icons/base/Next'; import { findScrollParents } from '../utils/DOM'; import CSSClassnames from '../utils/CSSClassnames'; import Intl from '../utils/Intl'; import { announce } from '../utils/Announcer'; import Props from '../utils/Props'; const CLASS_ROOT = CSSClassnames.CAROUSEL; /** * @description Image carousel. * * @example * import Carousel from 'grommet/components/Carousel'; * * <Carousel> * <Image src='/img/carousel-1.png' /> * <Image src='/img/carousel-2.png' /> * <Box pad='large' * colorIndex='neutral-3'> * <Box pad='medium' * colorIndex='neutral-2'> * Content inside of a Box element. * </Box> * </Box> * </Carousel> * */ export default class Carousel extends Component { constructor(props, context) { super(props, context); this._onSelect = this._onSelect.bind(this); this._stopAutoplay = this._stopAutoplay.bind(this); this._startAutoplay = this._startAutoplay.bind(this); this._onResize = this._onResize.bind(this); this._slidePrev = this._slidePrev.bind(this); this._slideNext = this._slideNext.bind(this); this._handleScroll = this._handleScroll.bind(this); this._announce = this._announce.bind(this); this.state = { activeIndex: props.activeIndex || 0, animate: typeof props.activeIndex == 'undefined', hideControls: ! props.persistentNav, sequence: 1, width: 0, slide: false }; } componentDidMount () { if (this.carouselRef) { this.setState({ width: this.carouselRef.offsetWidth }); window.addEventListener('resize', this._onResize); const Hammer = require('hammerjs'); this.hammer = new Hammer(this.carouselRef); this._updateHammer(); this._handleScroll(); const scrollParents = findScrollParents(this.carouselRef); scrollParents.forEach((scrollParent) => { scrollParent.addEventListener('scroll', this._handleScroll); }, this); } } componentWillReceiveProps(nextProps) { if ((nextProps.activeIndex || 0 === nextProps.activeIndex) && this.state.activeIndex !== nextProps.activeIndex) { this.setState( { activeIndex: nextProps.activeIndex, animate: true }, this._announce ); } } componentDidUpdate () { this._updateHammer(); } componentWillUnmount () { clearInterval(this._slideAnimation); window.removeEventListener('resize', this._onResize); const scrollParents = findScrollParents(this.carouselRef); scrollParents.forEach((scrollParent) => { scrollParent.removeEventListener('scroll', this._handleScroll); }, this); this._unmountHammer(); } _unmountHammer () { if (this.hammer) { this.hammer.stop(); this.hammer.destroy(); } this.hammer = undefined; } _updateHammer () { if (this.hammer) { this.hammer.get('swipe').set({ direction: Hammer.DIRECTION_HORIZONTAL }); this.hammer.off('panend'); this.hammer.on('panend', (event) => { if (event.direction === 4) { this._slidePrev(); } else if (event.direction === 2) { this._slideNext(); } }); } } _handleScroll () { const { autoplay } = this.props; const { slide } = this.state; const viewportHeight = document.documentElement.clientHeight; const carouselTopPosition = this.carouselRef.getBoundingClientRect().top; const carouselHeight = this.carouselRef.offsetHeight; const startScroll = viewportHeight - (carouselHeight / 2); if (autoplay && carouselTopPosition <= startScroll && carouselTopPosition >= -carouselHeight / 2) { if (slide === false) { this._setSlideInterval(); this.setState({ slide: true }); } } else { clearInterval(this._slideAnimation); this.setState({ slide: false }); } } _announce() { const { intl } = this.context; const slideNumber = Intl.getMessage(intl, 'Slide Number', { slideNumber: this.state.activeIndex + 1 }); const activatedMessage = Intl.getMessage(intl, 'Activated'); announce(`${slideNumber} ${activatedMessage}`, 'polite'); } _setSlideInterval () { const { autoplaySpeed } = this.props; clearInterval(this._slideAnimation); this._slideAnimation = setInterval(function () { const { children, infinite } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = (activeIndex + 1) % numSlides; if (! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce ); } if (!infinite && activeIndex === numSlides - 1) { clearInterval(this._slideAnimation); } if (this.props.onActive) { this.props.onActive(index); } }.bind(this), autoplaySpeed); } _onSelect (index) { if (! this.props.hasOwnProperty('activeIndex') && index !== this.state.activeIndex) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _stopAutoplay () { const { autoplay, persistentNav } = this.props; if (autoplay) { clearInterval(this._slideAnimation); } if (!persistentNav) { this.setState({ hideControls: false }); } } _startAutoplay () { const { activeIndex } = this.state; const { autoplay, children, infinite, persistentNav } = this.props; if (autoplay && (infinite || activeIndex !== children.length - 1) && // making sure to only start autoplay if the focus is not inside // the carousel !this.carouselRef.contains(document.activeElement)) { this._setSlideInterval(); } if (!persistentNav) { this.setState({ hideControls: true }); } } _onResize () { this.setState({ width: this.carouselRef.offsetWidth }); } _slidePrev () { const { children } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = !this.props.infinite && activeIndex === 0 ? activeIndex : (activeIndex + numSlides - 1) % numSlides; if(! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _slideNext () { const { children } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = !this.props.infinite && activeIndex === children.length - 1 ? activeIndex : (activeIndex + 1) % numSlides; if(! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _renderPrevButton () { const { infinite } = this.props; const { activeIndex } = this.state; const { intl } = this.context; let prevButton; if (infinite || activeIndex !== 0) { const prevMessage = Intl.getMessage(intl, 'Previous Slide'); prevButton = ( <Button icon={<PreviousIcon size="large" />} a11yTitle={prevMessage} className={`${CLASS_ROOT}__arrow ${CLASS_ROOT}__arrow--prev`} onClick={this._slidePrev} /> ); } return prevButton; } _renderNextButton () { const { children, infinite } = this.props; const { activeIndex } = this.state; const { intl } = this.context; let nextButton; if (infinite || activeIndex !== children.length - 1) { const nextMessage = Intl.getMessage(intl, 'Next Slide'); nextButton = ( <Button icon={<NextIcon size="large" />} a11yTitle={nextMessage} className={`${CLASS_ROOT}__arrow ${CLASS_ROOT}__arrow--next`} onClick={this._slideNext} /> ); } return nextButton; } render () { const { a11yTitle, children, className, ...props } = this.props; delete props.activeIndex; delete props.onActive; const restProps = Props.omit({...props}, Object.keys(Carousel.propTypes)); const { activeIndex, hideControls, width } = this.state; const { intl } = this.context; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--hide-controls`]: hideControls }, className ); const trackWidth = width * children.length; const trackOffset = width * activeIndex; const tiles = React.Children.map(children, (child, index) => { const ariaHidden = activeIndex !== index ? true : false; return ( <Tile className={`${CLASS_ROOT}__item`} aria-hidden={ariaHidden}> {child} </Tile> ); }); const controls = React.Children.map(children, (child, index) => { const active = index === activeIndex; const controlClasses = classnames( `${CLASS_ROOT}__control`, { [`${CLASS_ROOT}__control--active`]: active } ); const activateMessage = Intl.getMessage(intl, 'Activate'); const slideNumberMessage = Intl.getMessage(intl, 'Slide Number', { slideNumber: index + 1 }); let currentlyActiveMessage = ''; if (active) { currentlyActiveMessage = ( `(${Intl.getMessage(intl, 'Currently Active')})` ); } return ( <Button plain={true} onClick={this._onSelect.bind(this, index)} a11yTitle={ `${activateMessage} ${slideNumberMessage} ${currentlyActiveMessage}` }> <svg className={controlClasses} viewBox="0 0 24 24" version="1.1"> <circle cx={12} cy={12} r={6} /> </svg> </Button> ); }, this); const carouselMessage = a11yTitle || Intl.getMessage(intl, 'Carousel'); const trackClasses = classnames(`${CLASS_ROOT}__track`,{ [`${CLASS_ROOT}__track--animate`]: this.state.animate }); return ( <div ref={ref => this.carouselRef = ref} {...restProps} className={classes} role='group' aria-label={carouselMessage} onFocus={this._stopAutoplay} onBlur={this._startAutoplay} onMouseOver={this._stopAutoplay} onMouseOut={this._startAutoplay}> <div className={trackClasses} style={{ width: (trackWidth && trackWidth > 0) ? trackWidth : '', marginLeft: - trackOffset, marginRight: - (trackWidth - trackOffset - width) }}> <Tiles fill={true} responsive={false} wrap={false} direction="row"> {tiles} </Tiles> </div> {this._renderPrevButton()} {this._renderNextButton()} <Box className={CLASS_ROOT + "__controls"} direction="row" justify="center" responsive={false}> {controls} </Box> </div> ); } } Carousel.contextTypes = { intl: PropTypes.object }; Carousel.defaultProps = { autoplay: true, autoplaySpeed: 5000, infinite: true, persistentNav: true }; Carousel.propTypes = { a11yTitle: PropTypes.string, /** * @property {PropTypes.number} activeIndex - Active carousel index. Defaults to 0. If activeIndex is used, you will be in control. This means that you will need to use onActive callback to update your component state when the index changes. */ activeIndex: PropTypes.number, /** * @property {PropTypes.bool} autoplay - Whether the carousel should play automatically or not. Defaults to true. */ autoplay: PropTypes.bool, /** * @property {PropTypes.number} autoplaySpeed - How long the carousel should stay on each slide, in milliseconds. Defaults to 5000 (5 seconds). */ autoplaySpeed: PropTypes.number, /** * @property {PropTypes.bool} infinite - Whether the carousel should scroll back to the first slide when you get to the end, or stop at the last slide. Defaults to true. */ infinite: PropTypes.bool, /** * @property {PropTypes.func} onActive - Function that will be called with the active index when the currently active carousel changes. */ onActive: PropTypes.func, /** * @property {PropTypes.bool} persistentNav - Whether the navigational elements should always be shown, or only show when the user mouses over the carousel. Defaults to true. */ persistentNav: PropTypes.bool };
src/containers/App/App.js
hirzanalhakim/testKumparan
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { IndexLink } from 'react-router'; import { LinkContainer } from 'react-router-bootstrap'; import Navbar from 'react-bootstrap/lib/Navbar'; import Nav from 'react-bootstrap/lib/Nav'; import NavItem from 'react-bootstrap/lib/NavItem'; import Alert from 'react-bootstrap/lib/Alert'; import Helmet from 'react-helmet'; import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info'; import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth'; import { Notifs, InfoBar } from 'components'; import { push } from 'react-router-redux'; import config from 'config'; import { asyncConnect } from 'redux-connect'; @asyncConnect([{ promise: ({ store: { dispatch, getState } }) => { const promises = []; if (!isAuthLoaded(getState())) { promises.push(dispatch(loadAuth())); } if (!isInfoLoaded(getState())) { promises.push(dispatch(loadInfo())); } return Promise.all(promises); } }]) @connect( state => ({ notifs: state.notifs, user: state.auth.user }), { logout, pushState: push }) export default class App extends Component { static propTypes = { children: PropTypes.object.isRequired, router: PropTypes.object.isRequired, user: PropTypes.object, notifs: PropTypes.object.isRequired, logout: PropTypes.func.isRequired, pushState: PropTypes.func.isRequired }; static defaultProps = { user: null }; static contextTypes = { store: PropTypes.object.isRequired }; componentWillReceiveProps(nextProps) { if (!this.props.user && nextProps.user) { // login const redirect = this.props.router.location.query && this.props.router.location.query.redirect; this.props.pushState(redirect || '/loginSuccess'); } else if (this.props.user && !nextProps.user) { // logout this.props.pushState('/'); } } handleLogout = event => { event.preventDefault(); this.props.logout(); }; render() { const { user, notifs, children } = this.props; const styles = require('./App.scss'); return ( <div className={styles.app}> <Helmet {...config.app.head} /> <Navbar fixedTop> <Navbar.Header> <Navbar.Brand> <IndexLink to="/" activeStyle={{ color: '#33e0ff' }}> <div className={styles.brand} /> <span>{config.app.title}</span> </IndexLink> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav navbar> {user && <LinkContainer to="/chatFeathers"> <NavItem>Chat with Feathers</NavItem> </LinkContainer>} <LinkContainer to="/chat"> <NavItem>Chat</NavItem> </LinkContainer> <LinkContainer to="/widgets"> <NavItem>Widgets</NavItem> </LinkContainer> <LinkContainer to="/survey"> <NavItem>Survey</NavItem> </LinkContainer> <LinkContainer to="/about"> <NavItem>About Us</NavItem> </LinkContainer> <LinkContainer to="/coba"> <NavItem>Coba</NavItem> </LinkContainer> <LinkContainer to="/belajar"> <NavItem> Belajar</NavItem> </LinkContainer> {!user && <LinkContainer to="/login"> <NavItem>Login</NavItem> </LinkContainer>} {!user && <LinkContainer to="/register"> <NavItem>Register</NavItem> </LinkContainer>} {user && <LinkContainer to="/logout"> <NavItem className="logout-link" onClick={this.handleLogout}> Logout </NavItem> </LinkContainer>} </Nav> {user && <p className="navbar-text"> Logged in as <strong>{user.email}</strong>. </p>} <Nav navbar pullRight> <NavItem target="_blank" title="View on Github" href="https://github.com/erikras/react-redux-universal-hot-example" > <i className="fa fa-github" /> </NavItem> </Nav> </Navbar.Collapse> </Navbar> <div className={styles.appContent}> {notifs.global && <div className="container"> <Notifs className={styles.notifs} namespace="global" NotifComponent={props => <Alert bsStyle={props.kind}>{props.message}</Alert>} /> </div>} {children} </div> <InfoBar /> <div className="well text-center"> Have questions? Ask for help{' '} <a href="https://github.com/erikras/react-redux-universal-hot-example/issues" target="_blank" rel="noopener noreferrer" > on Github </a> {' '}or in the{' '} <a href="https://discord.gg/0ZcbPKXt5bZZb1Ko" target="_blank" rel="noopener noreferrer" > #react-redux-universal </a> {' '}Discord channel. </div> </div> ); } }
src/svg-icons/notification/disc-full.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDiscFull = (props) => ( <SvgIcon {...props}> <path d="M20 16h2v-2h-2v2zm0-9v5h2V7h-2zM10 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 10c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); NotificationDiscFull = pure(NotificationDiscFull); NotificationDiscFull.displayName = 'NotificationDiscFull'; NotificationDiscFull.muiName = 'SvgIcon'; export default NotificationDiscFull;
src/svg-icons/image/exposure-plus-1.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageExposurePlus1 = (props) => ( <SvgIcon {...props}> <path d="M10 7H8v4H4v2h4v4h2v-4h4v-2h-4V7zm10 11h-2V7.38L15 8.4V6.7L19.7 5h.3v13z"/> </SvgIcon> ); ImageExposurePlus1 = pure(ImageExposurePlus1); ImageExposurePlus1.displayName = 'ImageExposurePlus1'; ImageExposurePlus1.muiName = 'SvgIcon'; export default ImageExposurePlus1;
screens/CompanyProfileScreen/CompanyProfile.js
nattatorn-dev/expo-with-realworld
import React from 'react' import { StyleSheet, Text, View } from 'react-native' import PropTypes from 'prop-types' import { Colors } from 'constants' import { object } from 'utilities' import { Video } from '@components' const styles = StyleSheet.create( { container: { backgroundColor: '#fff', flexDirection: 'column', padding: 0, }, sectionCompanyProfile: { backgroundColor: 'transparent', flexDirection: 'column', minWidth: 12, paddingBottom: 30, paddingLeft: 20, paddingRight: 20, paddingTop: 30, }, rowDescription: { flexDirection: 'row', }, descriptionText: { color: Colors.textDescription, fontSize: 13, lineHeight: 20, textAlign: 'justify', }, rowTitle: { flexDirection: 'row', marginBottom: 14, }, titleText: { fontSize: 14, fontWeight: 'bold', }, } ) const CompanyProfile = ( { companyProfile: { description, urls, title } } ) => ( <View style={styles.container}> <Video shouldPlay uri={object.getFirstByKey( { item: urls, key: 'videos', } )} /> <View style={styles.sectionCompanyProfile}> <View style={styles.rowTitle}> <Text style={styles.titleText}>{title}</Text> </View> <View style={styles.rowDescription}> <Text style={styles.descriptionText}>{description}</Text> </View> </View> </View> ) CompanyProfile.propTypes = { companyProfile: PropTypes.shape( { description: PropTypes.string.isRequired, imgUrl: PropTypes.string, title: PropTypes.string.isRequired, } ), } export default CompanyProfile
frontend/src/Settings/Indexers/Indexers/AddIndexerModalContent.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Alert from 'Components/Alert'; import FieldSet from 'Components/FieldSet'; import Button from 'Components/Link/Button'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { kinds } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import AddIndexerItem from './AddIndexerItem'; import styles from './AddIndexerModalContent.css'; class AddIndexerModalContent extends Component { // // Render render() { const { isSchemaFetching, isSchemaPopulated, schemaError, usenetIndexers, torrentIndexers, onIndexerSelect, onModalClose } = this.props; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> {translate('AddIndexer')} </ModalHeader> <ModalBody> { isSchemaFetching && <LoadingIndicator /> } { !isSchemaFetching && !!schemaError && <div> {translate('UnableToAddANewIndexerPleaseTryAgain')} </div> } { isSchemaPopulated && !schemaError && <div> <Alert kind={kinds.INFO}> <div> {translate('RadarrSupportsAnyIndexer')} </div> <div> {translate('ForMoreInformationOnTheIndividualIndexers')} </div> </Alert> <FieldSet legend={translate('Usenet')}> <div className={styles.indexers}> { usenetIndexers.map((indexer) => { return ( <AddIndexerItem key={indexer.implementation} implementation={indexer.implementation} {...indexer} onIndexerSelect={onIndexerSelect} /> ); }) } </div> </FieldSet> <FieldSet legend={translate('Torrents')}> <div className={styles.indexers}> { torrentIndexers.map((indexer) => { return ( <AddIndexerItem key={indexer.implementation} implementation={indexer.implementation} {...indexer} onIndexerSelect={onIndexerSelect} /> ); }) } </div> </FieldSet> </div> } </ModalBody> <ModalFooter> <Button onPress={onModalClose} > {translate('Close')} </Button> </ModalFooter> </ModalContent> ); } } AddIndexerModalContent.propTypes = { isSchemaFetching: PropTypes.bool.isRequired, isSchemaPopulated: PropTypes.bool.isRequired, schemaError: PropTypes.object, usenetIndexers: PropTypes.arrayOf(PropTypes.object).isRequired, torrentIndexers: PropTypes.arrayOf(PropTypes.object).isRequired, onIndexerSelect: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default AddIndexerModalContent;
src/components/LoginFormComponent.js
loehnertz/HSRMMedialabTimetableApp
import React, { Component } from 'react'; import { Text, View, ScrollView, TouchableOpacity, ActivityIndicator, Linking, AsyncStorage, Platform } from 'react-native'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import * as Keychain from 'react-native-keychain'; import Orientation from 'react-native-orientation'; import { userChanged, passwordChanged, loginUser, setOrientation, endLoading } from '../actions' import { Card, CardSection, Button, Input } from './common'; import i18n from 'react-native-i18n'; import bundledTranslations from '../translations'; class LoginForm extends Component { state = { heightScrollView: -1 }; componentWillMount() { if (this.props.logout) { Keychain.resetGenericPassword() .then(() => { AsyncStorage.removeItem('masterdata'); AsyncStorage.removeItem('settings'); Actions.auth({ type: 'reset' }); this.props.endLoading(); }); } this.props.setOrientation(Orientation.getInitialOrientation()); } componentDidMount() { // The orientation on iOS causes several bugs. Therefore, I decided to not ship the (landscape) 'WeekView' before the major bugs are fixed if (Platform.OS === 'ios') { Orientation.lockToPortrait(); this.props.setOrientation('PORTRAIT'); } if (Platform.OS !== 'ios') { Orientation.addOrientationListener(this._orientationDidChange); // Add a listener for the change of the device orientation } } _orientationDidChange = (changedOrientation) => { this.props.setOrientation(changedOrientation); }; onUserChange(text) { this.props.userChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } onButtonPress() { this.props.loginUser(this.props.user, this.props.password); } renderButton() { if (this.props.loading) { return ( <View style={styles.spinner}> <ActivityIndicator size={'large'} /> </View> ); } return ( <Button onPress={this.onButtonPress.bind(this)}> Login </Button> ); } setViewHeight() { if (this.state.heightScrollView !== -1) { if (this.props.orientation === 'PORTRAIT') { return ({ height: this.state.heightScrollView - 55 }); } else if (this.props.orientation === 'LANDSCAPE') { return ({ height: this.state.heightScrollView + 55 }); } } } renderErrorNotice() { if (this.props.error.length > 0) { return ( <CardSection> <Text style={styles.errorText}> {this.props.error} </Text> </CardSection> ); } else { return (null); } } renderFooterPlatform() { if (Platform.OS === 'android') { return i18n.t('developed_by'); } else if (Platform.OS === 'ios') { return i18n.t('by'); } } render () { return ( <ScrollView onLayout={(layout) => this.setState({ heightScrollView: layout.nativeEvent.layout.height })}> <View style={this.setViewHeight()}> <Card style={styles.mainCard}> <CardSection> <Text style={styles.noticeText}> {i18n.t('login_notice')} </Text> </CardSection> <CardSection> <Input label={i18n.t('username')} placeholder="" onChangeText={this.onUserChange.bind(this)} value={this.props.user} /> </CardSection> <CardSection> <Input secureTextEntry label={i18n.t('password')} placeholder="" onChangeText={this.onPasswordChange.bind(this)} value={this.props.password} /> </CardSection> {this.renderErrorNotice()} <CardSection> {this.renderButton()} </CardSection> </Card> </View> <View style={styles.noticeFooter}> <View style={styles.noticeFooterContainer}> <Text style={styles.noticeFooterText}> {this.renderFooterPlatform()} Jakob Löhnertz ( </Text> <TouchableOpacity onPress={() => Linking.openURL('https://www.jakob.codes/')}> <Text style={[styles.noticeFooterText, styles.hyperlinkText]}>www.jakob.codes</Text> </TouchableOpacity> <Text style={styles.noticeFooterText}> ) </Text> </View> <View style={styles.noticeFooterContainer}> <Text style={styles.noticeFooterText}> {i18n.t('code_licensed_under')} </Text> <TouchableOpacity onPress={() => Linking.openURL('https://github.com/loehnertz/HSRMMedialabTimetableApp/blob/master/LICENSE')}> <Text style={[styles.noticeFooterText, styles.hyperlinkText]}> MIT License</Text> </TouchableOpacity> </View> </View> </ScrollView> ); } } i18n.fallbacks = true; i18n.translations = bundledTranslations; const styles = { errorText: { alignSelf: "center", color: "red" }, mainCard: { marginTop: (Platform.OS === 'ios') ? 20 : 10, }, noticeText: { fontWeight: "bold" }, noticeFooter: { flexDirection: "column", alignItems: "center", height: 55 }, noticeFooterContainer: { flexDirection: "row" }, noticeFooterText: { fontSize: 14, fontWeight: "bold" }, hyperlinkText: { color: "#E10019" }, spinner: { flex: 1, justifyContent: "center", alignItems: "center" } }; const mapStateToProps = state => { return { user: state.login.userField, password: state.login.passwordField, error: state.login.error, loading: state.login.loadingLogin, orientation: state.timetable.orientation } }; export default connect(mapStateToProps, { userChanged, passwordChanged, loginUser, setOrientation, endLoading })(LoginForm);
src/components/Starred/Styles.js
BastienAlvez/ReactNativeHue
import React from 'react'; import { StyleSheet, } from 'react-native'; var styles = StyleSheet.create({ }); module.exports = styles;
src/components/navbar.js
icartusacrimea/portfolio_reactredux
import React, { Component } from 'react'; class Navbar extends Component { constructor(props) { super(props); this.changeView2 = this.changeView2.bind(this); } changeView2(e) { e.preventDefault(); console.log(e.target.value); this.props.showSection(e.target.value); } render() { return ( <nav className="navbar navbar-inverse navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button onClick={this.changeView2} value="top" className="navbar-brand">top</button> <button onClick={this.changeView2} value="user" className="navbar-right" href="#">about</button> <button onClick={this.changeView2} value="projects" className="navbar-right" href="#">portfolio</button> </div> </div> </nav> ); } } export default Navbar;
app/javascript/mastodon/features/video/index.js
danhunsaker/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { is } from 'immutable'; import { throttle, debounce } from 'lodash'; import classNames from 'classnames'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen'; import { displayMedia, useBlurhash } from '../../initial_state'; import Icon from 'mastodon/components/icon'; import Blurhash from 'mastodon/components/blurhash'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, hide: { id: 'video.hide', defaultMessage: 'Hide video' }, expand: { id: 'video.expand', defaultMessage: 'Expand video' }, close: { id: 'video.close', defaultMessage: 'Close video' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, }); export const formatTime = secondsNum => { let hours = Math.floor(secondsNum / 3600); let minutes = Math.floor((secondsNum - (hours * 3600)) / 60); let seconds = secondsNum - (hours * 3600) - (minutes * 60); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`; }; export const findElementPosition = el => { let box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0, }; } const docEl = document.documentElement; const body = document.body; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const scrollLeft = window.pageXOffset || body.scrollLeft; const left = (box.left + scrollLeft) - clientLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const scrollTop = window.pageYOffset || body.scrollTop; const top = (box.top + scrollTop) - clientTop; return { left: Math.round(left), top: Math.round(top), }; }; export const getPointerPosition = (el, event) => { const position = {}; const box = findElementPosition(el); const boxW = el.offsetWidth; const boxH = el.offsetHeight; const boxY = box.top; const boxX = box.left; let pageY = event.pageY; let pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; }; export const fileNameFromURL = str => { const url = new URL(str); const pathname = url.pathname; const index = pathname.lastIndexOf('/'); return pathname.substring(index + 1); }; export default @injectIntl class Video extends React.PureComponent { static propTypes = { preview: PropTypes.string, frameRate: PropTypes.string, src: PropTypes.string.isRequired, alt: PropTypes.string, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, currentTime: PropTypes.number, onOpenVideo: PropTypes.func, onCloseVideo: PropTypes.func, detailed: PropTypes.bool, inline: PropTypes.bool, editable: PropTypes.bool, alwaysVisible: PropTypes.bool, cacheWidth: PropTypes.func, visible: PropTypes.bool, onToggleVisibility: PropTypes.func, deployPictureInPicture: PropTypes.func, intl: PropTypes.object.isRequired, blurhash: PropTypes.string, autoPlay: PropTypes.bool, volume: PropTypes.number, muted: PropTypes.bool, componetIndex: PropTypes.number, }; static defaultProps = { frameRate: '25', }; state = { currentTime: 0, duration: 0, volume: 0.5, paused: true, dragging: false, containerWidth: this.props.width, fullscreen: false, hovered: false, muted: false, revealed: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'), }; setPlayerRef = c => { this.player = c; if (this.player) { this._setDimensions(); } } _setDimensions () { const width = this.player.offsetWidth; if (this.props.cacheWidth) { this.props.cacheWidth(width); } this.setState({ containerWidth: width, }); } setVideoRef = c => { this.video = c; if (this.video) { this.setState({ volume: this.video.volume, muted: this.video.muted }); } } setSeekRef = c => { this.seek = c; } setVolumeRef = c => { this.volume = c; } handleClickRoot = e => e.stopPropagation(); handlePlay = () => { this.setState({ paused: false }); this._updateTime(); } handlePause = () => { this.setState({ paused: true }); } _updateTime () { requestAnimationFrame(() => { if (!this.video) return; this.handleTimeUpdate(); if (!this.state.paused) { this._updateTime(); } }); } handleTimeUpdate = () => { this.setState({ currentTime: this.video.currentTime, duration:this.video.duration, }); } handleVolumeMouseDown = e => { document.addEventListener('mousemove', this.handleMouseVolSlide, true); document.addEventListener('mouseup', this.handleVolumeMouseUp, true); document.addEventListener('touchmove', this.handleMouseVolSlide, true); document.addEventListener('touchend', this.handleVolumeMouseUp, true); this.handleMouseVolSlide(e); e.preventDefault(); e.stopPropagation(); } handleVolumeMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseVolSlide, true); document.removeEventListener('mouseup', this.handleVolumeMouseUp, true); document.removeEventListener('touchmove', this.handleMouseVolSlide, true); document.removeEventListener('touchend', this.handleVolumeMouseUp, true); } handleMouseVolSlide = throttle(e => { const { x } = getPointerPosition(this.volume, e); if(!isNaN(x)) { this.setState({ volume: x }, () => { this.video.volume = x; }); } }, 15); handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove, true); document.addEventListener('mouseup', this.handleMouseUp, true); document.addEventListener('touchmove', this.handleMouseMove, true); document.addEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: true }); this.video.pause(); this.handleMouseMove(e); e.preventDefault(); e.stopPropagation(); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove, true); document.removeEventListener('mouseup', this.handleMouseUp, true); document.removeEventListener('touchmove', this.handleMouseMove, true); document.removeEventListener('touchend', this.handleMouseUp, true); this.setState({ dragging: false }); this.video.play(); } handleMouseMove = throttle(e => { const { x } = getPointerPosition(this.seek, e); const currentTime = this.video.duration * x; if (!isNaN(currentTime)) { this.setState({ currentTime }, () => { this.video.currentTime = currentTime; }); } }, 15); seekBy (time) { const currentTime = this.video.currentTime + time; if (!isNaN(currentTime)) { this.setState({ currentTime }, () => { this.video.currentTime = currentTime; }); } } handleVideoKeyDown = e => { // On the video element or the seek bar, we can safely use the space bar // for playback control because there are no buttons to press if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); this.togglePlay(); } } handleKeyDown = e => { const frameTime = 1 / this.getFrameRate(); switch(e.key) { case 'k': e.preventDefault(); e.stopPropagation(); this.togglePlay(); break; case 'm': e.preventDefault(); e.stopPropagation(); this.toggleMute(); break; case 'f': e.preventDefault(); e.stopPropagation(); this.toggleFullscreen(); break; case 'j': e.preventDefault(); e.stopPropagation(); this.seekBy(-10); break; case 'l': e.preventDefault(); e.stopPropagation(); this.seekBy(10); break; case ',': e.preventDefault(); e.stopPropagation(); this.seekBy(-frameTime); break; case '.': e.preventDefault(); e.stopPropagation(); this.seekBy(frameTime); break; } // If we are in fullscreen mode, we don't want any hotkeys // interacting with the UI that's not visible if (this.state.fullscreen) { e.preventDefault(); e.stopPropagation(); if (e.key === 'Escape') { exitFullscreen(); } } } togglePlay = () => { if (this.state.paused) { this.setState({ paused: false }, () => this.video.play()); } else { this.setState({ paused: true }, () => this.video.pause()); } } toggleFullscreen = () => { if (isFullscreen()) { exitFullscreen(); } else { requestFullscreen(this.player); } } componentDidMount () { document.addEventListener('fullscreenchange', this.handleFullscreenChange, true); document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true); window.addEventListener('scroll', this.handleScroll); window.addEventListener('resize', this.handleResize, { passive: true }); } componentWillUnmount () { window.removeEventListener('scroll', this.handleScroll); window.removeEventListener('resize', this.handleResize); document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true); document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true); if (!this.state.paused && this.video && this.props.deployPictureInPicture) { this.props.deployPictureInPicture('video', { src: this.props.src, currentTime: this.video.currentTime, muted: this.video.muted, volume: this.video.volume, }); } } componentWillReceiveProps (nextProps) { if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) { this.setState({ revealed: nextProps.visible }); } } componentDidUpdate (prevProps, prevState) { if (prevState.revealed && !this.state.revealed && this.video) { this.video.pause(); } } handleResize = debounce(() => { if (this.player) { this._setDimensions(); } }, 250, { trailing: true, }); handleScroll = throttle(() => { if (!this.video) { return; } const { top, height } = this.video.getBoundingClientRect(); const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0); if (!this.state.paused && !inView) { this.video.pause(); if (this.props.deployPictureInPicture) { this.props.deployPictureInPicture('video', { src: this.props.src, currentTime: this.video.currentTime, muted: this.video.muted, volume: this.video.volume, }); } this.setState({ paused: true }); } }, 150, { trailing: true }) handleFullscreenChange = () => { this.setState({ fullscreen: isFullscreen() }); } handleMouseEnter = () => { this.setState({ hovered: true }); } handleMouseLeave = () => { this.setState({ hovered: false }); } toggleMute = () => { const muted = !this.video.muted; this.setState({ muted }, () => { this.video.muted = muted; }); } toggleReveal = () => { if (this.props.onToggleVisibility) { this.props.onToggleVisibility(); } else { this.setState({ revealed: !this.state.revealed }); } } handleLoadedData = () => { const { currentTime, volume, muted, autoPlay } = this.props; if (currentTime) { this.video.currentTime = currentTime; } if (volume !== undefined) { this.video.volume = volume; } if (muted !== undefined) { this.video.muted = muted; } if (autoPlay) { this.video.play(); } } handleProgress = () => { const lastTimeRange = this.video.buffered.length - 1; if (lastTimeRange > -1) { this.setState({ buffer: Math.ceil(this.video.buffered.end(lastTimeRange) / this.video.duration * 100) }); } } handleVolumeChange = () => { this.setState({ volume: this.video.volume, muted: this.video.muted }); } handleOpenVideo = () => { this.video.pause(); this.props.onOpenVideo({ startTime: this.video.currentTime, autoPlay: !this.state.paused, defaultVolume: this.state.volume, componetIndex: this.props.componetIndex, }); } handleCloseVideo = () => { this.video.pause(); this.props.onCloseVideo(); } getFrameRate () { if (this.props.frameRate && isNaN(this.props.frameRate)) { // The frame rate is returned as a fraction string so we // need to convert it to a number return this.props.frameRate.split('/').reduce((p, c) => p / c); } return this.props.frameRate; } render () { const { preview, src, inline, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, editable, blurhash } = this.props; const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state; const progress = Math.min((currentTime / duration) * 100, 100); const playerStyle = {}; let { width, height } = this.props; if (inline && containerWidth) { width = containerWidth; height = containerWidth / (16/9); playerStyle.height = height; } let preload; if (this.props.currentTime || fullscreen || dragging) { preload = 'auto'; } else if (detailed) { preload = 'metadata'; } else { preload = 'none'; } let warning; if (sensitive) { warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />; } else { warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />; } return ( <div role='menuitem' className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable })} style={playerStyle} ref={this.setPlayerRef} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onClick={this.handleClickRoot} onKeyDown={this.handleKeyDown} tabIndex={0} > <Blurhash hash={blurhash} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': revealed, })} dummy={!useBlurhash} /> {(revealed || editable) && <video ref={this.setVideoRef} src={src} poster={preview} preload={preload} role='button' tabIndex='0' aria-label={alt} title={alt} width={width} height={height} volume={volume} onClick={this.togglePlay} onKeyDown={this.handleVideoKeyDown} onPlay={this.handlePlay} onPause={this.handlePause} onLoadedData={this.handleLoadedData} onProgress={this.handleProgress} onVolumeChange={this.handleVolumeChange} />} <div className={classNames('spoiler-button', { 'spoiler-button--hidden': revealed || editable })}> <button type='button' className='spoiler-button__overlay' onClick={this.toggleReveal}> <span className='spoiler-button__overlay__label'>{warning}</span> </button> </div> <div className={classNames('video-player__controls', { active: paused || hovered })}> <div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}> <div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} /> <div className='video-player__seek__progress' style={{ width: `${progress}%` }} /> <span className={classNames('video-player__seek__handle', { active: dragging })} tabIndex='0' style={{ left: `${progress}%` }} onKeyDown={this.handleVideoKeyDown} /> </div> <div className='video-player__buttons-bar'> <div className='video-player__buttons left'> <button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay} autoFocus={detailed}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button> <button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button> <div className={classNames('video-player__volume', { active: this.state.hovered })} onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}> <div className='video-player__volume__current' style={{ width: `${volume * 100}%` }} /> <span className={classNames('video-player__volume__handle')} tabIndex='0' style={{ left: `${volume * 100}%` }} /> </div> {(detailed || fullscreen) && ( <span className='video-player__time'> <span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span> <span className='video-player__time-sep'>/</span> <span className='video-player__time-total'>{formatTime(Math.floor(duration))}</span> </span> )} </div> <div className='video-player__buttons right'> {(!onCloseVideo && !editable && !fullscreen && !this.props.alwaysVisible) && <button type='button' title={intl.formatMessage(messages.hide)} aria-label={intl.formatMessage(messages.hide)} className='player-button' onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>} {(!fullscreen && onOpenVideo) && <button type='button' title={intl.formatMessage(messages.expand)} aria-label={intl.formatMessage(messages.expand)} className='player-button' onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>} {onCloseVideo && <button type='button' title={intl.formatMessage(messages.close)} aria-label={intl.formatMessage(messages.close)} className='player-button' onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>} <button type='button' title={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} className='player-button' onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button> </div> </div> </div> </div> ); } }
examples/universal/client/index.js
bkniffler/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
v0.0.1/app/footer.js
reactjs-id/reactjs-id.github.io
import React from 'react'; import axios from 'axios'; class Footer extends React.Component { render() { return ( <footer className="footer" id="join-us"> <div className="content" style={{paddingTop: 0}}> <div className=""> <p style={{paddingTop: '20px', textAlign: 'center'}}><a className="button" href="https://github.com/reactjs-id/reactjs-id.github.io#kontribusi">+ Ingin Kontribusi? Tambah Konten?</a></p> </div> <div className="copyright" style={{paddingTop: 0}}> <ul> <li>© 2016</li> <li><a href="https://www.facebook.com/groups/442974152553174/">Komunitas ReactJS Indonesia</a></li> <li>Dibangun dengan <a href="http://reactjs.com/" target="_blank">ReactJS</a>.</li> </ul> </div> </div> </footer> ); } }; export default Footer;
src/common/MyDialog.js
IACJ/react-datastructer
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import '../common/common.css'; /** * Dialog with action buttons. The actions are passed in as an array of React objects, * in this example [FlatButtons](/#/components/flat-button). * * You can also close this dialog by clicking outside the dialog, or with the 'Esc' key. */ export default class MyDialog extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; handleNewWindow =() => { window.open (this.props.src); } render() { const {primary,secondary,src} = this.props; const actions = [ src? <FlatButton label="查看该数据结构源代码(JS版)" secondary={true} onTouchTap={this.handleNewWindow} /> : null, <FlatButton label="太长不看..." primary={true} onTouchTap={this.handleClose} />, <FlatButton label="了解" primary={true} keyboardFocused={true} onTouchTap={this.handleClose} />, ]; return ( <div style={{display:'inline'} }> <RaisedButton label={this.props.label} className='btn' primary={primary} secondary={secondary} onTouchTap={this.handleOpen} /> <Dialog title={this.props.title} actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > {this.props.children} </Dialog> </div> ); } }
src/components/Home.js
juanesarango/github-battle
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Home extends Component { render() { return ( <div className="home-container"> <h1>Github Battle: Battle your friends... and stuff.</h1> <Link className="button" to="/battle"> Battle </Link> </div> ); } } export default Home;
Console/app/node_modules/antd/es/anchor/Anchor.js
RisenEsports/RisenEsports.github.io
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import addEventListener from 'rc-util/es/Dom/addEventListener'; import Affix from '../affix'; import getScroll from '../_util/getScroll'; import getRequestAnimationFrame from '../_util/getRequestAnimationFrame'; function getDefaultTarget() { return window; } function getOffsetTop(element) { if (!element) { return 0; } if (!element.getClientRects().length) { return 0; } var rect = element.getBoundingClientRect(); if (rect.width || rect.height) { var doc = element.ownerDocument; var docElem = doc.documentElement; return rect.top - docElem.clientTop; } return rect.top; } function easeInOutCubic(t, b, c, d) { var cc = c - b; t /= d / 2; if (t < 1) { return cc / 2 * t * t * t + b; } return cc / 2 * ((t -= 2) * t * t + 2) + b; } var reqAnimFrame = getRequestAnimationFrame(); function scrollTo(href) { var offsetTop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var target = arguments[2]; var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {}; var scrollTop = getScroll(target(), true); var targetElement = document.getElementById(href.substring(1)); if (!targetElement) { return; } var eleOffsetTop = getOffsetTop(targetElement); var targetScrollTop = scrollTop + eleOffsetTop - offsetTop; var startTime = Date.now(); var frameFunc = function frameFunc() { var timestamp = Date.now(); var time = timestamp - startTime; window.scrollTo(window.pageXOffset, easeInOutCubic(time, scrollTop, targetScrollTop, 450)); if (time < 450) { reqAnimFrame(frameFunc); } else { callback(); } }; reqAnimFrame(frameFunc); history.pushState(null, '', href); } var Anchor = function (_React$Component) { _inherits(Anchor, _React$Component); function Anchor(props) { _classCallCheck(this, Anchor); var _this = _possibleConstructorReturn(this, (Anchor.__proto__ || Object.getPrototypeOf(Anchor)).call(this, props)); _this.handleScroll = function () { if (_this.animating) { return; } var _this$props = _this.props, offsetTop = _this$props.offsetTop, bounds = _this$props.bounds; _this.setState({ activeLink: _this.getCurrentAnchor(offsetTop, bounds) }); }; _this.handleScrollTo = function (link) { var _this$props2 = _this.props, offsetTop = _this$props2.offsetTop, _this$props2$target = _this$props2.target, target = _this$props2$target === undefined ? getDefaultTarget : _this$props2$target; _this.animating = true; _this.setState({ activeLink: link }); scrollTo(link, offsetTop, target, function () { _this.animating = false; }); }; _this.updateInk = function () { if (typeof document === 'undefined') { return; } var prefixCls = _this.props.prefixCls; var linkNode = ReactDOM.findDOMNode(_this).getElementsByClassName(prefixCls + '-link-title-active')[0]; if (linkNode) { _this.refs.ink.style.top = linkNode.offsetTop + linkNode.clientHeight / 2 - 4.5 + 'px'; } }; _this.state = { activeLink: null }; _this.links = []; return _this; } _createClass(Anchor, [{ key: 'getChildContext', value: function getChildContext() { var _this2 = this; return { antAnchor: { registerLink: function registerLink(link) { if (!_this2.links.includes(link)) { _this2.links.push(link); } }, unregisterLink: function unregisterLink(link) { var index = _this2.links.indexOf(link); if (index !== -1) { _this2.links.splice(index, 1); } }, activeLink: this.state.activeLink, scrollTo: this.handleScrollTo } }; } }, { key: 'componentDidMount', value: function componentDidMount() { var getTarget = this.props.target || getDefaultTarget; this.scrollEvent = addEventListener(getTarget(), 'scroll', this.handleScroll); this.handleScroll(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.scrollEvent) { this.scrollEvent.remove(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this.updateInk(); } }, { key: 'getCurrentAnchor', value: function getCurrentAnchor() { var offsetTop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var bounds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5; var activeLink = ''; if (typeof document === 'undefined') { return activeLink; } var linkSections = []; this.links.forEach(function (link) { var target = document.getElementById(link.substring(1)); if (target && getOffsetTop(target) < offsetTop + bounds) { var top = getOffsetTop(target); linkSections.push({ link: link, top: top }); } }); if (linkSections.length) { var maxSection = linkSections.reduce(function (prev, curr) { return curr.top > prev.top ? curr : prev; }); return maxSection.link; } return ''; } }, { key: 'render', value: function render() { var _props = this.props, prefixCls = _props.prefixCls, _props$className = _props.className, className = _props$className === undefined ? '' : _props$className, style = _props.style, offsetTop = _props.offsetTop, affix = _props.affix, showInkInFixed = _props.showInkInFixed, children = _props.children; var activeLink = this.state.activeLink; var inkClass = classNames(prefixCls + '-ink-ball', { visible: activeLink }); var wrapperClass = classNames(className, prefixCls + '-wrapper'); var anchorClass = classNames(prefixCls, { 'fixed': !affix && !showInkInFixed }); var anchorContent = React.createElement( 'div', { className: wrapperClass, style: style }, React.createElement( 'div', { className: anchorClass }, React.createElement( 'div', { className: prefixCls + '-ink' }, React.createElement('span', { className: inkClass, ref: 'ink' }) ), children ) ); return !affix ? anchorContent : React.createElement( Affix, { offsetTop: offsetTop }, anchorContent ); } }]); return Anchor; }(React.Component); export default Anchor; Anchor.defaultProps = { prefixCls: 'ant-anchor', affix: true, showInkInFixed: false }; Anchor.childContextTypes = { antAnchor: PropTypes.object };
src/components/statusLabel/statusLabel.stories.js
teamleadercrm/teamleader-ui
import React from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import StatusLabel from './StatusLabel'; export default { component: StatusLabel, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Status Label'), parameters: { design: { type: 'figma', url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=246%3A1041', }, }, }; export const Basic = (args) => <StatusLabel {...args}>Status label</StatusLabel>;
src/components/Projects/ProjectsPage.js
liutongchen/liutong-chen-website
import React from 'react'; import personalInfo from '../../../src/info'; import {Row, Col} from 'react-bootstrap'; import ProjectComponents from './projectComponents'; import ScrollToTopOnMount from '../commons/ScrollToTopOnMount'; class ProjectsPage extends React.Component { render() { return ( <div> <ScrollToTopOnMount/> <Row id="projectIntro"> <img src="https://image.shutterstock.com/z/stock-vector-cartoon-girl-types-on-a-laptop-97727552.jpg" alt="Image" className="img-circle" id="projectIntroImg"/> <Col xs={8} xsOffset={2} sm={8} smOffset={2} mdOffset={4} md={4}> <h2>What I've Done</h2> <p>Here's some of the work I have done so far. To learn more about the projects I have done, please go to my <a href={personalInfo.basicInfo.github}>github</a>.</p> </Col> </Row> <ProjectComponents projectsList={personalInfo.projects}/> </div> ); } } export default ProjectsPage;
src/_core/index.js
asidiali/pivotal.press
import { HomeView, Layout, ProjectStoriesView, ProjectsView, } from '../views'; import { Route, Router, hashHistory, } from 'react-router'; import App from './app'; import React from 'react'; import injectTapEventPlugin from 'react-tap-event-plugin'; import ls from 'local-storage'; import {render} from 'react-dom'; injectTapEventPlugin(); function requireAuth() { if (!ls('pp-api') || !ls('pp-me')) setTimeout(hashHistory.push('/'), 500); } const main = () => { ga('create', 'UA-86630001-1', 'auto'); ga('send', 'pageview'); render( <Router history={hashHistory}> <Route component={App}> <Route path="/" component={HomeView} /> <Route component={Layout} onEnter={requireAuth}> <Route path="/projects" component={ProjectsView} /> <Route path="/projects/:projectId" component={ProjectStoriesView} /> </Route> </Route> </Router>, document.getElementById('app') ); } const loadedStates = ['complete', 'loaded', 'interactive']; if (loadedStates.includes(document.readyState) && document.body) { main(); } else { document.addEventListener('DOMContentLoaded', main, false); } (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
presentation/slides/redux.js
tdmckinn/react-es-presentation
import React from 'react'; import { Heading, Slide, Text, Layout, Fill, List, ListItem } from 'spectacle'; const images = { reduxLogo: require('../../assets/images/redux.svg'), reduxFlow: require('../../assets/images/reduxFlow.jpg') }; const purple = '#764ABC'; const ReduxSlides = [ <Slide transition={['zoom', 'fade']} bgImage={images.reduxLogo} bgColor="black" bgDarken={0.75} bgSize="contain" bgRepeat="no-repeat" > <Heading textColor={purple} size={4}> Redux </Heading> <Text textColor="#fff">Client Side State Management</Text> </Slide>, <Slide transition={['zoom', 'fade']} bgColor="black" bgDarken={0.85}> <Heading size={4} caps textColor={purple} bgColor="white" margin={10}> What is Redux? </Heading> <Layout> <Fill> <Text textColor="white">Three Principles:</Text> <List textColor="white"> <ListItem>Single Source of Truth</ListItem> <ListItem>State is read-only</ListItem> <ListItem>Changes are made with pure functions</ListItem> </List> </Fill> </Layout> </Slide>, <Slide transition={['zoom', 'fade']} bgColor="black" bgDarken={0.85}> <Heading size={4} caps textColor={purple} bgColor="white" margin={10}> Let's explore Redux </Heading> <Layout> <Fill> <List textColor="white"> <ListItem> Actions - {` type: 'LIKE_ARTICLE', articleId: 42 `} </ListItem> <ListItem> Store </ListItem> <ListItem> Reducers - pureFunctionReducer(state = {}, action) </ListItem> <ListItem> Dataflow </ListItem> </List> </Fill> </Layout> </Slide>, <Slide transition={['zoom']} bgColor="black" > <Heading size={4} textColor="tertiary"> Redux Flow </Heading> <img src="http://staltz.com/img/mvu-unidir-ui-arch.jpg" style={{ maxWidth: 700 }} /> </Slide>, <Slide bgColor={purple}> <Heading> Why Redux ? </Heading> <Text> Pure functions, Encorugages best practices in JS development, Dominiate flux varient, and provides integration to enable state machines... </Text> </Slide>, <Slide bgColor={purple}> <Heading size={4} caps textColor={purple} bgColor="black" > What's the learning curve ? Easy </Heading> </Slide> ]; export default ReduxSlides;
public/components/wz-menu/wz-menu-management.js
wazuh/wazuh-kibana-app
/* * Wazuh app - React component for registering agents. * Copyright (C) 2015-2022 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component } from 'react'; import { EuiFlexItem, EuiFlexGroup, EuiSideNav, EuiIcon, EuiButtonEmpty, EuiToolTip } from '@elastic/eui'; import { WzRequest } from '../../react-services/wz-request'; import { connect } from 'react-redux'; import { AppNavigate } from '../../react-services/app-navigate' import { WAZUH_MENU_MANAGEMENT_SECTIONS_ID } from '../../../common/constants'; import { WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID } from '../../../common/wazu-menu/wz-menu-management.cy'; class WzMenuManagement extends Component { constructor(props) { super(props); this.state = { // TODO: Fix the selected section selectedItemName: null }; this.managementSections = { management: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.MANAGEMENT, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.MANAGEMENT, text: 'Management', }, administration: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.ADMINISTRATION, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.ADMINISTRATION, text: 'Administration', }, ruleset: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.RULESET, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.RULESET, text: 'Ruleset', }, rules: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.RULES, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.RULES, text: 'Rules', }, decoders: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.DECODERS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.DECODERS, text: 'Decoders', }, lists: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.CDB_LISTS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.CDB_LISTS, text: 'CDB lists', }, groups: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.GROUPS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.GROUPS, text: 'Groups', }, configuration: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.CONFIGURATION, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.CONFIGURATION, text: 'Configuration', }, statusReports: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.STATUS_AND_REPORTS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.STATUS_AND_REPORTS, text: 'Status and reports', }, status: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.STATUS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.STATUS, text: 'Status', }, cluster: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.CLUSTER, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.CLUSTER, text: 'Cluster', }, logs: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.LOGS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.LOGS, text: 'Logs', }, reporting: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.REPORTING, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.REPORTING, text: 'Reporting', }, statistics: { id: WAZUH_MENU_MANAGEMENT_SECTIONS_ID.STATISTICS, cyTestId: WAZUH_MENU_MANAGEMENT_SECTIONS_CY_TEST_ID.STATISTICS, text: 'Statistics', }, }; this.paths = { rules: '/rules', decoders: '/decoders', lists: '/lists/files' }; this.wzReq = WzRequest; } UNSAFE_componentWillReceiveProps(nextProps) { // You don't have to do this check first, but it can help prevent an unneeded render if (nextProps.section !== this.state.selectedItemName) { this.setState({ selectedItemName: nextProps.section }); } } clickMenuItem = (ev, section) => { this.props.closePopover(); AppNavigate.navigateToModule(ev, 'manager', { tab: section }) }; createItem = (item, data = {}) => { // NOTE: Duplicate `name` values will cause `id` collisions. return { ...data, id: item.id, name: item.text, 'data-test-subj': item.cyTestId, isSelected: this.props.state.section === item.id, onClick: () => { }, onMouseDown: (ev) => this.clickMenuItem(ev, item.id) }; }; render() { const sideNavAdmin = [ { name: this.managementSections.administration.text, id: this.managementSections.administration.id, id: 0, disabled: true, icon: <EuiIcon type="managementApp" color="primary" />, items: [ this.createItem(this.managementSections.rules), this.createItem(this.managementSections.decoders), this.createItem(this.managementSections.lists), this.createItem(this.managementSections.groups), this.createItem(this.managementSections.configuration), ], } ]; const sideNavStatus = [ { name: this.managementSections.statusReports.text, id: this.managementSections.statusReports.id, disabled: true, icon: <EuiIcon type="reportingApp" color="primary" />, items: [ this.createItem(this.managementSections.status), this.createItem(this.managementSections.cluster), this.createItem(this.managementSections.statistics), this.createItem(this.managementSections.logs), this.createItem(this.managementSections.reporting) ] } ]; return ( <div className="WzManagementSideMenu"> <EuiFlexGroup> <EuiFlexItem grow={false} style={{ marginLeft: 14 }}> <EuiButtonEmpty iconType="apps" onClick={() => { this.props.closePopover(); window.location.href = '#/manager'; }}> Management directory </EuiButtonEmpty> </EuiFlexItem> </EuiFlexGroup> <EuiFlexGroup responsive={false}> <EuiFlexItem grow={false}> <EuiSideNav items={sideNavAdmin} style={{ padding: '4px 12px' }} /> </EuiFlexItem> <EuiFlexItem grow={false}> <EuiSideNav items={sideNavStatus} style={{ padding: '4px 12px' }} /> </EuiFlexItem> </EuiFlexGroup> </div> ); } } const mapStateToProps = state => { return { state: state.rulesetReducers, }; }; export default connect( mapStateToProps, )(WzMenuManagement);
src/components/App.js
henrikra/reactive-movies
import React, { Component } from 'react'; import $ from 'jquery'; import SearchBar from './SearchBar'; import MovieList from './MovieList'; import InfiniteScroll from './InfiniteScroll'; import ResultsHeader from './ResultsHeader'; import {apiKey} from '../apiKey'; require('../styles/style.scss'); export default class App extends Component { state = { movies: [], loading: false, page: 1, type: '', error: '' } getMovies = (query, page, type, currentMovies = []) => { this.setState({ loading: true, movies: currentMovies }); $.get('http://www.omdbapi.com/?apikey=' + apiKey + '&s=' + query + '&type=' + type + '&page=' + page, (result) => { if (result.Search) { this.setState({ movies: currentMovies.concat(result.Search), loading: false, query: query, page: page, type: type, error: '' }); } else { this.setState({ error: result.Error, query: query, loading: false }); } }); } handleQuerySubmit = (query, type) => { this.getMovies(query, 1, type); } handleShowMoreClick = page => { this.getMovies(this.state.query, page, this.state.type, this.state.movies); } render() { return ( <div className="app"> <SearchBar onQuerySubmit={this.handleQuerySubmit} loading={this.state.loading} /> <div className="container"> <ResultsHeader error={this.state.error} query={this.state.query} hasMovies={this.state.movies.length} /> <MovieList movies={this.state.movies} /> <InfiniteScroll loading={this.state.loading} movieCount={this.state.movies.length} onShowMoreClick={this.handleShowMoreClick} page={this.state.page} /> </div> <footer>&copy; {new Date().getFullYear()} Henrik Raitasola</footer> </div> ); } }
src/route/enduser/UserList.js
simors/yjbAdmin
import React from 'react'; import {connect} from 'react-redux'; import {Table, Popconfirm, message} from 'antd'; import moment from 'moment'; import {action, selector} from './redux'; import {action as authAction, selector as authSelector, AUTH_USER_STATUS} from '../../util/auth/'; class UserList extends React.Component { constructor(props) { super(props); this.columns = [{ title: '用户名', dataIndex: 'nickname', }, { title: '手机号码', dataIndex: 'mobilePhoneNumber', }, { title: '所在地区', render: (record) => { const {province={}, city={}} = record; const {label: provinceStr=''} = province; const {label: cityStr=''} = city; let area = provinceStr; if (cityStr) { area = `${provinceStr}/${cityStr}`; } return ( <span> {area} </span> ); }, }, { title: '最近登录时间', render: (record) => { const {updatedAt} = record; const updatedAtStr = moment(updatedAt).format('LLL'); return ( <span> {updatedAtStr} </span> ); }, }, { title: '状态', render: (record) => { const {mpStatus} = record; let statusStr = '正常'; let color = 'inherit'; if (mpStatus === AUTH_USER_STATUS.MP_DISABLED) { statusStr = '禁用'; color = 'red'; } return ( <span style={{color}}>{statusStr}</span> ); }, }, { title: '操作', key: 'action', render: (record) => { const onDisable = () => { this.props.updateUser({ params: { id: record.id, mpStatus: AUTH_USER_STATUS.MP_DISABLED, }, onSuccess: () => { this.props.listEndUsers({ limit: 1000, onStart: () => { this.props.changeLoading({loading: true}); }, onComplete: () => { this.props.changeLoading({loading: false}); }, }); }, onFailure: (code) => { message.error(`禁用用户失败, 错误:${code}`); }, }); }; const onEnable = () => { this.props.updateUser({ params: { id: record.id, mpStatus: AUTH_USER_STATUS.MP_NORMAL, }, onSuccess: () => { this.props.listEndUsers({ limit: 1000, onStart: () => { this.props.changeLoading({loading: true}); }, onComplete: () => { this.props.changeLoading({loading: false}); }, }); }, onFailure: (code) => { message.error(`启用用户失败, 错误:${code}`); }, }); }; return ( <span> {(() => { if (record.mpStatus === AUTH_USER_STATUS.MP_DISABLED) { return ( <Popconfirm title='确定要启用该用户吗?' onConfirm={onEnable}> <a style={{color: 'blue'}}>启用</a> </Popconfirm> ); } else { return ( <Popconfirm title='确定要禁用该用户吗?' onConfirm={onDisable}> <a style={{color: 'blue'}}>禁用</a> </Popconfirm> ); } })()} </span> ); }, }]; } componentDidMount() { this.props.listEndUsers({ limit: 1000, onStart: () => { this.props.changeLoading({loading: true}); }, onComplete: () => { this.props.changeLoading({loading: false}); }, }); } rowKey = (record) => { return record.id; }; onSelectChange = (selectedRowKeys, selectedRows) => { this.props.updateSelectedUserIds({selected: selectedRowKeys}); if (selectedRowKeys.length === 1) { } }; render() { const {loading} = this.props; if (this.props.users === undefined) return null; const rowSelection = { type: 'radio', selectedRowKeys: this.props.selectedUserIds, onChange: this.onSelectChange, }; return ( <Table columns={this.columns} dataSource={this.props.users} rowKey={this.rowKey} rowSelection={rowSelection} loading={loading} /> ); } } const mapStateToProps = (appState, ownProps) => { const loading = selector.selectLoading(appState); const selectedUserIds = selector.selectSelectedUserIds(appState); const users = authSelector.selectEndUsers(appState); return { loading, selectedUserIds, users, }; }; const mapDispatchToProps = { ...action, ...authAction, }; export default connect(mapStateToProps, mapDispatchToProps)(UserList);
app/javascript/mastodon/features/notifications/index.js
riku6460/chikuwagoddon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandNotifications, scrollTopNotifications } from '../../actions/notifications'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import NotificationContainer from './containers/notification_container'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import FilterBarContainer from './containers/filter_bar_container'; import { createSelector } from 'reselect'; import { List as ImmutableList } from 'immutable'; import { debounce } from 'lodash'; import ScrollableList from '../../components/scrollable_list'; import LoadGap from '../../components/load_gap'; const messages = defineMessages({ title: { id: 'column.notifications', defaultMessage: 'Notifications' }, }); const getNotifications = createSelector([ state => state.getIn(['settings', 'notifications', 'quickFilter', 'show']), state => state.getIn(['settings', 'notifications', 'quickFilter', 'active']), state => ImmutableList(state.getIn(['settings', 'notifications', 'shows']).filter(item => !item).keys()), state => state.getIn(['notifications', 'items']), ], (showFilterBar, allowedType, excludedTypes, notifications) => { if (!showFilterBar || allowedType === 'all') { // used if user changed the notification settings after loading the notifications from the server // otherwise a list of notifications will come pre-filtered from the backend // we need to turn it off for FilterBar in order not to block ourselves from seeing a specific category return notifications.filterNot(item => item !== null && excludedTypes.includes(item.get('type'))); } return notifications.filter(item => item !== null && allowedType === item.get('type')); }); const mapStateToProps = state => ({ showFilterBar: state.getIn(['settings', 'notifications', 'quickFilter', 'show']), notifications: getNotifications(state), isLoading: state.getIn(['notifications', 'isLoading'], true), isUnread: state.getIn(['notifications', 'unread']) > 0, hasMore: state.getIn(['notifications', 'hasMore']), }); export default @connect(mapStateToProps) @injectIntl class Notifications extends React.PureComponent { static propTypes = { columnId: PropTypes.string, notifications: ImmutablePropTypes.list.isRequired, showFilterBar: PropTypes.bool.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, isLoading: PropTypes.bool, isUnread: PropTypes.bool, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, }; static defaultProps = { trackScroll: true, }; componentWillUnmount () { this.handleLoadOlder.cancel(); this.handleScrollToTop.cancel(); this.handleScroll.cancel(); this.props.dispatch(scrollTopNotifications(false)); } handleLoadGap = (maxId) => { this.props.dispatch(expandNotifications({ maxId })); }; handleLoadOlder = debounce(() => { const last = this.props.notifications.last(); this.props.dispatch(expandNotifications({ maxId: last && last.get('id') })); }, 300, { leading: true }); handleScrollToTop = debounce(() => { this.props.dispatch(scrollTopNotifications(true)); }, 100); handleScroll = debounce(() => { this.props.dispatch(scrollTopNotifications(false)); }, 100); handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('NOTIFICATIONS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setColumnRef = c => { this.column = c; } handleMoveUp = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) - 1; this._selectChild(elementIndex); } handleMoveDown = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) + 1; this._selectChild(elementIndex); } _selectChild (index) { const element = this.column.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { element.focus(); } } render () { const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore, showFilterBar } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." />; let scrollableContent = null; const filterBarContainer = showFilterBar ? (<FilterBarContainer />) : null; if (isLoading && this.scrollableContent) { scrollableContent = this.scrollableContent; } else if (notifications.size > 0 || hasMore) { scrollableContent = notifications.map((item, index) => item === null ? ( <LoadGap key={'gap:' + notifications.getIn([index + 1, 'id'])} disabled={isLoading} maxId={index > 0 ? notifications.getIn([index - 1, 'id']) : null} onClick={this.handleLoadGap} /> ) : ( <NotificationContainer key={item.get('id')} notification={item} accountId={item.get('account')} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} /> )); } else { scrollableContent = null; } this.scrollableContent = scrollableContent; const scrollContainer = ( <ScrollableList scrollKey={`notifications-${columnId}`} trackScroll={!pinned} isLoading={isLoading} showLoading={isLoading && notifications.size === 0} hasMore={hasMore} emptyMessage={emptyMessage} onLoadMore={this.handleLoadOlder} onScrollToTop={this.handleScrollToTop} onScroll={this.handleScroll} shouldUpdateScroll={shouldUpdateScroll} > {scrollableContent} </ScrollableList> ); return ( <Column ref={this.setColumnRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='bell' active={isUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer /> </ColumnHeader> {filterBarContainer} {scrollContainer} </Column> ); } }
client/modules/core/routes.js
LikeJasper/mantra-plus
import React from 'react'; import { mount } from 'react-mounter'; import MainLayout from './containers/main_layout'; import PostList from './containers/postlist'; import Post from './containers/post'; import NewPost from './containers/newpost'; export default function (injectDeps, { FlowRouter }) { const MainLayoutCtx = injectDeps(MainLayout); FlowRouter.route('/', { name: 'posts.list', action() { mount(MainLayoutCtx, { content: () => (<PostList />), }); }, }); FlowRouter.route('/post/:postId', { name: 'posts.single', action({ postId }) { mount(MainLayoutCtx, { content: () => (<Post postId={postId} />), }); }, }); FlowRouter.route('/new-post', { name: 'newpost', action() { mount(MainLayoutCtx, { content: () => (<NewPost />), }); }, }); }
ignite/DevScreens/PluginExamplesScreen.js
littletimo/beer-counter
// Fair Warning: PluginExamples has a good bit of Ignite automation in editing. // Though robust, if you should modify this file, review your changes with us // As to not break the automated addition/subtractions. import React from 'react' import { View, ScrollView, Text, TouchableOpacity, Image } from 'react-native' import { StackNavigator } from 'react-navigation' import { Images } from './DevTheme' // Examples Render Engine import ExamplesRegistry from '../../App/Services/ExamplesRegistry' import '../Examples/Components/vectorExample.js' // Styles import styles from './Styles/PluginExamplesScreenStyles' class PluginExamplesScreen extends React.Component { render () { return ( <View style={styles.mainContainer}> <Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' /> <TouchableOpacity onPress={() => this.props.navigation.goBack(null)} style={{ position: 'absolute', paddingTop: 30, paddingHorizontal: 5, zIndex: 10 }}> <Image source={Images.backButton} /> </TouchableOpacity> <ScrollView style={styles.container}> <View style={{alignItems: 'center', paddingTop: 60}}> <Image source={Images.usageExamples} style={styles.logo} /> <Text style={styles.titleText}>Plugin Examples</Text> </View> <View style={styles.section}> <Text style={styles.sectionText} > The Plugin Examples screen is a playground for 3rd party libs and logic proofs. Items on this screen can be composed of multiple components working in concert. Functionality demos of libs and practices </Text> </View> {ExamplesRegistry.renderPluginExamples()} <View style={styles.screenButtons} /> </ScrollView> </View> ) } } export default StackNavigator({ PluginExamplesScreen: {screen: PluginExamplesScreen} }, { cardStyle: { opacity: 1, backgroundColor: '#3e243f' }, headerMode: 'none', initialRouteName: 'PluginExamplesScreen' })
app/javascript/mastodon/components/poll.js
maa123/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Motion from 'mastodon/features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import escapeTextContentForBrowser from 'escape-html'; import emojify from 'mastodon/features/emoji/emoji'; import RelativeTimestamp from './relative_timestamp'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ closed: { id: 'poll.closed', defaultMessage: 'Closed', }, voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer', }, votes: { id: 'poll.votes', defaultMessage: '{votes, plural, one {# vote} other {# votes}}', }, }); const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => { obj[`:${emoji.get('shortcode')}:`] = emoji.toJS(); return obj; }, {}); export default @injectIntl class Poll extends ImmutablePureComponent { static propTypes = { poll: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, disabled: PropTypes.bool, refresh: PropTypes.func, onVote: PropTypes.func, }; state = { selected: {}, expired: null, }; static getDerivedStateFromProps (props, state) { const { poll, intl } = props; const expires_at = poll.get('expires_at'); const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < intl.now(); return (expired === state.expired) ? null : { expired }; } componentDidMount () { this._setupTimer(); } componentDidUpdate () { this._setupTimer(); } componentWillUnmount () { clearTimeout(this._timer); } _setupTimer () { const { poll, intl } = this.props; clearTimeout(this._timer); if (!this.state.expired) { const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now(); this._timer = setTimeout(() => { this.setState({ expired: true }); }, delay); } } _toggleOption = value => { if (this.props.poll.get('multiple')) { const tmp = { ...this.state.selected }; if (tmp[value]) { delete tmp[value]; } else { tmp[value] = true; } this.setState({ selected: tmp }); } else { const tmp = {}; tmp[value] = true; this.setState({ selected: tmp }); } } handleOptionChange = ({ target: { value } }) => { this._toggleOption(value); }; handleOptionKeyPress = (e) => { if (e.key === 'Enter' || e.key === ' ') { this._toggleOption(e.target.getAttribute('data-index')); e.stopPropagation(); e.preventDefault(); } } handleVote = () => { if (this.props.disabled) { return; } this.props.onVote(Object.keys(this.state.selected)); }; handleRefresh = () => { if (this.props.disabled) { return; } this.props.refresh(); }; renderOption (option, optionIndex, showResults) { const { poll, disabled, intl } = this.props; const pollVotesCount = poll.get('voters_count') || poll.get('votes_count'); const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100; const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count')); const active = !!this.state.selected[`${optionIndex}`]; const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex)); let titleEmojified = option.get('title_emojified'); if (!titleEmojified) { const emojiMap = makeEmojiMap(poll); titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap); } return ( <li key={option.get('title')}> <label className={classNames('poll__option', { selectable: !showResults })}> <input name='vote-options' type={poll.get('multiple') ? 'checkbox' : 'radio'} value={optionIndex} checked={active} onChange={this.handleOptionChange} disabled={disabled} /> {!showResults && ( <span className={classNames('poll__input', { checkbox: poll.get('multiple'), active })} tabIndex='0' role={poll.get('multiple') ? 'checkbox' : 'radio'} onKeyPress={this.handleOptionKeyPress} aria-checked={active} aria-label={option.get('title')} data-index={optionIndex} /> )} {showResults && ( <span className='poll__number' title={intl.formatMessage(messages.votes, { votes: option.get('votes_count'), })} > {Math.round(percent)}% </span> )} <span className='poll__option__text translate' dangerouslySetInnerHTML={{ __html: titleEmojified }} /> {!!voted && <span className='poll__voted'> <Icon id='check' className='poll__voted__mark' title={intl.formatMessage(messages.voted)} /> </span>} </label> {showResults && ( <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}> {({ width }) => <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} /> } </Motion> )} </li> ); } render () { const { poll, intl } = this.props; const { expired } = this.state; if (!poll) { return null; } const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />; const showResults = poll.get('voted') || expired; const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item); let votesCount = null; if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) { votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />; } else { votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />; } return ( <div className='poll'> <ul> {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))} </ul> <div className='poll__footer'> {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>} {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>} {votesCount} {poll.get('expires_at') && <span> · {timeRemaining}</span>} </div> </div> ); } }
app/components/activities/TagsCard.js
cmilfont/zonaextrema
import React from 'react'; export default function TagsCard( {description=''} ) { const createTag = (tag, index) => tag.length? <a key={ `tag${index}` }>{tag.trim()}</a> : ''; const list = description.split(' ') .map( createTag ); return ( <div className="mdl-cell--hide-phone tags"> {list} </div> ); } TagsCard.propTypes = { description: React.PropTypes.string };
src/features/tab-view/favorites/index.js
rldona/react-native-tab-view-seed
import React, { Component } from 'react'; import { ScrollView, StyleSheet, Text, View } from 'react-native'; import * as firebase from 'firebase'; import * as colors from '../../../common/colors'; import * as themoviedb from '../../../services/movies-service'; import * as userService from '../../../services/user-service'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import FavoriteList from './favorite-list'; export default class Favorites extends Component { constructor(props) { super(props); this.state = { saved: [], viewed: [], favorite: [] }; } componentDidMount() { let user = firebase.auth().currentUser; if (user) { firebase.database().ref('users/' + user.uid + '/list/favorite').on('value', (snapshot) => { if (snapshot.val()) { let favoritesListLimit = []; for (let i = 0; i < snapshot.val().length; i++) { if (i < 2) { favoritesListLimit.unshift(snapshot.val()[i]); } } this.setState({ favorite: favoritesListLimit }); } else { this.setState({ favorite: [] }); } }); firebase.database().ref('users/' + user.uid + '/list/saved').on('value', (snapshot) => { if (snapshot.val()) { let favoritesListLimit = []; for (let i = 0; i < snapshot.val().length; i++) { if (i < 2) { favoritesListLimit.unshift(snapshot.val()[i]); } } this.setState({ saved: favoritesListLimit }); } else { this.setState({ saved: [] }); } }); firebase.database().ref('users/' + user.uid + '/list/viewed').on('value', (snapshot) => { if (snapshot.val()) { let favoritesListLimit = []; for (let i = 0; i < snapshot.val().length; i++) { if (i < 2) { favoritesListLimit.unshift(snapshot.val()[i]); } } this.setState({ viewed: favoritesListLimit }); } else { this.setState({ viewed: [] }); } }); } } render() { return ( <ScrollView style={styles.container}> <FavoriteList title="Las quiero ver" list={this.state.saved} type="saved" /> <FavoriteList title="Las he visto" list={this.state.viewed} type="viewed" /> <FavoriteList title="Mis favoritas" list={this.state.favorite} type="favorite" /> </ScrollView> ); } } const styles = StyleSheet.create({ container: { // height: height, paddingHorizontal: 10, paddingVertical: 15 } });
src/routes/dashboard/components/sales.js
terryli1643/daoke-react-c
import React from 'react' import PropTypes from 'prop-types' import styles from './sales.less' import classnames from 'classnames' import { color } from '../../../utils' import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts' function Sales ({ data }) { return ( <div className={styles.sales}> <div className={styles.title}>Yearly Sales</div> <ResponsiveContainer minHeight={360}> <LineChart data={data}> <Legend verticalAlign="top" content={prop => { const { payload } = prop return (<ul className={classnames({ [styles.legend]: true, clearfix: true })}> {payload.map((item, key) => <li key={key}><span className={styles.radiusdot} style={{ background: item.color }} />{item.value}</li>)} </ul>) }} /> <XAxis dataKey="name" axisLine={{ stroke: color.borderBase, strokeWidth: 1 }} tickLine={false} /> <YAxis axisLine={false} tickLine={false} /> <CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray="3 3" /> <Tooltip wrapperStyle={{ border: 'none', boxShadow: '4px 4px 40px rgba(0, 0, 0, 0.05)' }} content={content => { const list = content.payload.map((item, key) => <li key={key} className={styles.tipitem}><span className={styles.radiusdot} style={{ background: item.color }} />{`${item.name}:${item.value}`}</li>) return <div className={styles.tooltip}><p className={styles.tiptitle}>{content.label}</p><ul>{list}</ul></div> }} /> <Line type="monotone" dataKey="Food" stroke={color.purple} strokeWidth={3} dot={{ fill: color.purple }} activeDot={{ r: 5, strokeWidth: 0 }} /> <Line type="monotone" dataKey="Clothes" stroke={color.red} strokeWidth={3} dot={{ fill: color.red }} activeDot={{ r: 5, strokeWidth: 0 }} /> <Line type="monotone" dataKey="Electronics" stroke={color.green} strokeWidth={3} dot={{ fill: color.green }} activeDot={{ r: 5, strokeWidth: 0 }} /> </LineChart> </ResponsiveContainer> </div> ) } Sales.propTypes = { data: PropTypes.array, } export default Sales
src/client/components/set-name.js
caseywebdev/bruteball
import React from 'react'; import store from '../utils/store'; const handleKeyDown = ({key, target: {value: name}}) => { if (key === 'Enter') store.run({query: ['updateUser!', {name}]}); }; export default () => <input defaultValue={store.get(['user', 'name'])} onKeyDown={handleKeyDown} />;
client/index.js
KCPSoftware/KCPS-React-Starterkit
/* eslint-disable global-require */ import React from 'react'; import { render } from 'react-dom'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import asyncBootstrapper from 'react-async-bootstrapper'; import { AsyncComponentProvider } from 'react-async-component'; import configureStore from '../shared/redux/configureStore'; import { JobProvider } from 'react-jobs'; import { Provider } from 'react-redux'; import { loadUser, userNotLoggedIn } from '../shared/actions/userActions'; import './polyfills'; import ReactHotLoader from './components/ReactHotLoader'; import App from '../shared/components'; // Get the DOM Element that will host our React application. const container = document.querySelector('#app'); // Does the userReducers's browser support the HTML5 history API? // If the userReducers's browser doesn't support the HTML5 history API then we // will force full page refreshes on each page change. const supportsHistory = 'pushState' in window.history; // Get any rehydrateState for the async components. // eslint-disable-next-line no-underscore-dangle const asyncComponentsRehydrateState = window.__ASYNC_COMPONENTS_REHYDRATE_STATE__; const store = configureStore( // Server side rendering would have mounted our state on this global. window.__APP_STATE__, // eslint-disable-line no-underscore-dangle ); // Get any "rehydrate" state sent back by the server // eslint-disable-next-line no-underscore-dangle const rehydrateState = window.__JOBS_STATE__; var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "Other"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown"; }, searchString: function (data) { for (var i = 0; i < data.length; i++) { var dataString = data[i].string; this.versionSearchString = data[i].subString; if (dataString.indexOf(data[i].subString) !== -1) { return data[i].identity; } } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index === -1) { return; } var rv = dataString.indexOf("rv:"); if (this.versionSearchString === "Trident" && rv !== -1) { return parseFloat(dataString.substring(rv + 3)); } else { return parseFloat(dataString.substring(index + this.versionSearchString.length + 1)); } }, dataBrowser: [ {string: navigator.userAgent, subString: "Edge", identity: "MS Edge"}, {string: navigator.userAgent, subString: "MSIE", identity: "Explorer"}, {string: navigator.userAgent, subString: "Trident", identity: "Explorer"}, {string: navigator.userAgent, subString: "Firefox", identity: "Firefox"}, {string: navigator.userAgent, subString: "Opera", identity: "Opera"}, {string: navigator.userAgent, subString: "OPR", identity: "Opera"}, {string: navigator.userAgent, subString: "Chrome", identity: "Chrome"}, {string: navigator.userAgent, subString: "Safari", identity: "Safari"} ] }; BrowserDetect.init(); let isUnsupportedBrower = false; // if(BrowserDetect.browser === "Explorer" || BrowserDetect.browser === "MS Edge") { // isUnsupportedBrower = true; // } /** * Renders the given React Application component. */ function renderApp(TheApp) { // Firstly, define our full application component, wrapping the given // component app with a browser based version of react router. let app; if (isUnsupportedBrower) { app = <div> Dear client,<br /> <br /> Unfortunately our client portal is not yet supported by the browsers:<br /> Edge and Internet Explorer.<br /> <br /> Please use the browsers <a href="https://www.google.com/chrome/" target="_blank">Chrome</a>, <a href="https://www.mozilla.org/en-US/firefox/new/" target="_blank">Firefox</a>, <a href="https://support.apple.com/downloads/safari" target="_blank">Safari</a> or <a href="http://www.opera.com/download" target="_blank">Opera</a> to enter our online client portal. Our apologies for the inconvenience caused.<br /> <br /> We hope to assist you soon. For questions, please contact us via info@ttmtax.nl.<br /> <br /> Best regards,<br /> <br /> Team TTMTAX </div> } else { app = ( <ReactHotLoader> <AsyncComponentProvider rehydrateState={asyncComponentsRehydrateState}> <JobProvider rehydrateState={rehydrateState}> <BrowserRouter forceRefresh={!supportsHistory}> <Provider store={store}> <TheApp /> </Provider> </BrowserRouter> </JobProvider> </AsyncComponentProvider> </ReactHotLoader> ); } // We use the react-async-component in order to support code splitting of // our bundle output. It's important to use this helper. // @see https://github.com/ctrlplusb/react-async-component asyncBootstrapper(app).then(() => render(app, container)); } const token = localStorage.getItem('token'); if (token !== null) { store.dispatch(loadUser(token)); } else { store.dispatch(userNotLoggedIn()); } // Execute the first render of our app. renderApp(App); // This registers our service worker for asset caching and offline support. // Keep this as the last item, just in case the code execution failed (thanks // to react-boilerplate for that tip.) require('./registerServiceWorker'); // The following is needed so that we can support hot reloading our application. if (process.env.BUILD_FLAG_IS_DEV === 'true' && module.hot) { // Accept changes to this file for hot reloading. module.hot.accept('./index.js'); // Any changes to our App will cause a hotload re-render. module.hot.accept('../shared/components', () => { renderApp(require('../shared/components').default); }); }
js/App/Components/TabViews/SubViews/GenericDashboardTile.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { View } from '../../../../BaseComponents'; import DashboardShadowTile from './DashboardShadowTile'; type Props = { style: Object, }; class GenericDashboardTile extends View { constructor(props: Props) { super(props); } render(): React$Element<any> { const { item, tileWidth } = this.props; return ( <DashboardShadowTile item={item} isEnabled={true} name={item.name} type={''} tileWidth={tileWidth} style={[ this.props.style, { width: tileWidth, height: tileWidth, }, ]}> <View style={{ flex: 30 }}/> </DashboardShadowTile> ); } } module.exports = (GenericDashboardTile: Object);
src/app/core/atoms/icon/icons/settings.js
blowsys/reservo
import React from 'react'; const Settings = (props) => <svg {...props} x="0px" y="0px" viewBox="0 0 14.173 14.173"><path d="M12.327,6.346h-0.825c-0.114-0.685-0.382-1.317-0.769-1.859l0.583-0.583c0.17-0.17,0.17-0.445,0-0.615 l-0.432-0.432c-0.17-0.17-0.445-0.17-0.615,0L9.686,3.44C9.144,3.052,8.512,2.785,7.827,2.671V1.846c0-0.24-0.195-0.435-0.435-0.435 l-0.611,0c-0.24,0-0.435,0.195-0.435,0.435v0.825C5.661,2.785,5.029,3.052,4.487,3.44L3.904,2.857c-0.17-0.17-0.445-0.17-0.615,0 L2.857,3.289c-0.17,0.17-0.17,0.445,0,0.615L3.44,4.487C3.052,5.03,2.784,5.661,2.67,6.346H1.846c-0.24,0-0.435,0.195-0.435,0.435 l0,0.611c0,0.24,0.195,0.435,0.435,0.435l0.825,0C2.785,8.512,3.052,9.144,3.44,9.686l-0.583,0.583c-0.17,0.17-0.17,0.445,0,0.615 l0.432,0.432c0.17,0.17,0.445,0.17,0.615,0l0.583-0.583c0.542,0.387,1.174,0.655,1.859,0.769l0,0.825 c0,0.24,0.195,0.435,0.435,0.435h0.611c0.24,0,0.435-0.195,0.435-0.435v-0.825c0.685-0.114,1.317-0.382,1.859-0.769l0.583,0.583 c0.17,0.17,0.445,0.17,0.615,0l0.432-0.432c0.17-0.17,0.17-0.445,0-0.615l-0.583-0.583c0.387-0.542,0.655-1.174,0.769-1.858h0.825 c0.24,0,0.435-0.195,0.435-0.435V6.781C12.763,6.541,12.568,6.346,12.327,6.346z M7.087,8.336c-0.69,0-1.249-0.559-1.249-1.249 c0-0.69,0.559-1.249,1.249-1.249c0.69,0,1.249,0.559,1.249,1.249C8.335,7.776,7.776,8.336,7.087,8.336z"/></svg>; export default Settings;
src/js/index.js
grommet/next-sample
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; const element = document.getElementById('content'); ReactDOM.render(<App />, element); document.body.classList.remove('loading');
src/svg-icons/image/looks-one.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooksOne = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-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-5 14h-2V9h-2V7h4v10z"/> </SvgIcon> ); ImageLooksOne = pure(ImageLooksOne); ImageLooksOne.displayName = 'ImageLooksOne'; ImageLooksOne.muiName = 'SvgIcon'; export default ImageLooksOne;
node_modules/redux-devtools-log-monitor/src/LogMonitorButton.js
HasanSa/hackathon
import React from 'react'; import brighten from './brighten'; import shouldPureComponentUpdate from 'react-pure-render/function'; const styles = { base: { cursor: 'pointer', fontWeight: 'bold', borderRadius: 3, padding: 4, marginLeft: 3, marginRight: 3, marginTop: 5, marginBottom: 5, flexGrow: 1, display: 'inline-block', fontSize: '0.8em', color: 'white', textDecoration: 'none' } }; export default class LogMonitorButton extends React.Component { shouldComponentUpdate = shouldPureComponentUpdate; constructor(props) { super(props); this.handleMouseEnter = this.handleMouseEnter.bind(this); this.handleMouseLeave = this.handleMouseLeave.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.onClick = this.onClick.bind(this); this.state = { hovered: false, active: false }; } handleMouseEnter() { this.setState({ hovered: true }); } handleMouseLeave() { this.setState({ hovered: false }); } handleMouseDown() { this.setState({ active: true }); } handleMouseUp() { this.setState({ active: false }); } onClick() { if (!this.props.enabled) { return; } if (this.props.onClick) { this.props.onClick(); } } render() { let style = { ...styles.base, backgroundColor: this.props.theme.base02 }; if (this.props.enabled && this.state.hovered) { style = { ...style, backgroundColor: brighten(this.props.theme.base02, 0.2) }; } if (!this.props.enabled) { style = { ...style, opacity: 0.2, cursor: 'text', backgroundColor: 'transparent' }; } return ( <a onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onClick={this.onClick} style={style}> {this.props.children} </a> ); } }
src/views/Feed/FeedContent.js
Semantic-Org/Semantic-UI-React
import cx from 'clsx' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, createShorthand, customPropTypes, getElementType, getUnhandledProps, } from '../../lib' import FeedDate from './FeedDate' import FeedExtra from './FeedExtra' import FeedMeta from './FeedMeta' import FeedSummary from './FeedSummary' function FeedContent(props) { const { children, className, content, extraImages, extraText, date, meta, summary } = props const classes = cx('content', className) const rest = getUnhandledProps(FeedContent, props) const ElementType = getElementType(FeedContent, props) if (!childrenUtils.isNil(children)) { return ( <ElementType {...rest} className={classes}> {children} </ElementType> ) } return ( <ElementType {...rest} className={classes}> {createShorthand(FeedDate, (val) => ({ content: val }), date, { autoGenerateKey: false })} {createShorthand(FeedSummary, (val) => ({ content: val }), summary, { autoGenerateKey: false, })} {content} {createShorthand(FeedExtra, (val) => ({ text: true, content: val }), extraText, { autoGenerateKey: false, })} {createShorthand(FeedExtra, (val) => ({ images: val }), extraImages, { autoGenerateKey: false, })} {createShorthand(FeedMeta, (val) => ({ content: val }), meta, { autoGenerateKey: false })} </ElementType> ) } FeedContent.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** An event can contain a date. */ date: customPropTypes.itemShorthand, /** Shorthand for FeedExtra with images. */ extraImages: FeedExtra.propTypes.images, /** Shorthand for FeedExtra with text. */ extraText: customPropTypes.itemShorthand, /** Shorthand for FeedMeta. */ meta: customPropTypes.itemShorthand, /** Shorthand for FeedSummary. */ summary: customPropTypes.itemShorthand, } export default FeedContent
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js
ConnectedHomes/create-react-web-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; export default () => ( <span id="feature-shell-env-variables"> {process.env.REACT_APP_SHELL_ENV_MESSAGE}. </span> );
src/parser/druid/feral/modules/talents/SavageRoarUptime.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import { TooltipElement } from 'common/Tooltip'; class SavageRoarUptime extends Analyzer { constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SAVAGE_ROAR_TALENT.id); } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.SAVAGE_ROAR_TALENT.id) / this.owner.fightDuration; } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.90, major: 0.80, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <> Your <SpellLink id={SPELLS.SAVAGE_ROAR_TALENT.id} /> uptime can be improved. You should refresh the buff once it has reached its <TooltipElement content="The last 30% of the DoT's duration. When you refresh during this time you don't lose any duration in the process.">pandemic window</TooltipElement>, don't wait for it to wear off. You may also consider switching to <SpellLink id={SPELLS.SOUL_OF_THE_FOREST_TALENT_FERAL.id} /> which is simpler to use and provides more damage in many situations. </> ) .icon(SPELLS.SAVAGE_ROAR_TALENT.icon) .actual(`${formatPercentage(actual)}% uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SAVAGE_ROAR_TALENT.id} />} value={`${formatPercentage(this.uptime)}%`} label="Savage Roar uptime" position={STATISTIC_ORDER.OPTIONAL(0)} /> ); } } export default SavageRoarUptime;
src/browser/main.js
vacuumlabs/este
import React from 'react'; import ReactDOM from 'react-dom'; import configureReporting from '../common/configureReporting'; import configureStore from '../common/configureStore'; import createEngine from 'redux-storage-engine-localstorage'; import createRoutes from './createRoutes'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import { addLocaleData } from 'react-intl'; import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux'; // App supported locales are defined in src/server/config.js // Note the explicit enumeration, that's because static analysis ftw. import cs from 'react-intl/locale-data/cs'; import de from 'react-intl/locale-data/de'; import en from 'react-intl/locale-data/en'; import es from 'react-intl/locale-data/es'; import fr from 'react-intl/locale-data/fr'; import pt from 'react-intl/locale-data/pt'; import ro from 'react-intl/locale-data/ro'; [cs, de, en, es, fr, pt, ro].forEach(locale => addLocaleData(locale)); const initialState = window.__INITIAL_STATE__; const reportingMiddleware = configureReporting({ appVersion: initialState.config.appVersion, sentryUrl: initialState.config.sentryUrl, unhandledRejection: fn => window.addEventListener('unhandledrejection', fn) }); const store = configureStore({ createEngine, initialState, platformMiddleware: [reportingMiddleware, routerMiddleware(browserHistory)] }); const history = syncHistoryWithStore(browserHistory, store); const routes = createRoutes(store.getState); ReactDOM.render( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider> , document.getElementById('app') );
client/templateComponent.js
mordrax/cotwmtor
import React from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; import * as actions from '/actions/index.js'; import * as cotw from '/core/cotwContent.js'; export const ComponentName = ({}) => ( <div className="ComponentName-component"> </div> ); ComponentName.PropTypes = { //React.PropTypes.string.isRequired, //React.PropTypes.func.isRequired, //React.PropTypes.object.isRequired, //React.PropTypes.number.isRequired }; export const mapState = state => { return {} }; export const mapDispatch = dispatch => { return {} }; export default connect( mapState, mapDispatch)(ComponentName);
client/me/notification-settings/controller.js
allendav/wp-calypso
/** * External dependencies */ import React from 'react'; /** * Internal dependencies */ import analytics from 'analytics'; import i18n from 'lib/mixins/i18n'; import userSettings from 'lib/user-settings'; import titleActions from 'lib/screen-title/actions'; import { renderWithReduxStore } from 'lib/react-helpers'; import devicesFactory from 'lib/devices'; import sitesFactory from 'lib/sites-list'; import userFactory from 'lib/user'; const ANALYTICS_PAGE_TITLE = 'Me'; const devices = devicesFactory(); const sites = sitesFactory(); const user = userFactory(); export default { notifications( context ) { const NotificationsComponent = require( 'me/notification-settings/main' ), basePath = context.path; titleActions.setTitle( i18n.translate( 'Notifications', { textOnly: true } ) ); analytics.pageView.record( basePath, ANALYTICS_PAGE_TITLE + ' > Notifications' ); renderWithReduxStore( React.createElement( NotificationsComponent, { user: user, userSettings: userSettings, blogs: sites, devices: devices, path: context.path } ), document.getElementById( 'primary' ), context.store ); }, comments( context ) { const CommentSettingsComponent = require( 'me/notification-settings/comment-settings' ), basePath = context.path; titleActions.setTitle( i18n.translate( 'Comments on other sites', { textOnly: true } ) ); analytics.pageView.record( basePath, ANALYTICS_PAGE_TITLE + ' > Notifications > Comments on other sites' ); renderWithReduxStore( React.createElement( CommentSettingsComponent, { user: user, devices: devices, path: context.path } ), document.getElementById( 'primary' ), context.store ); }, updates( context ) { const WPcomSettingsComponent = require( 'me/notification-settings/wpcom-settings' ), basePath = context.path; titleActions.setTitle( i18n.translate( 'Updates from WordPress.com', { textOnly: true } ) ); analytics.pageView.record( basePath, ANALYTICS_PAGE_TITLE + ' > Notifications > Updates from WordPress.com' ); renderWithReduxStore( React.createElement( WPcomSettingsComponent, { user: user, devices: devices, path: context.path } ), document.getElementById( 'primary' ), context.store ); }, notificationSubscriptions( context ) { const NotificationSubscriptions = require( 'me/notification-settings/reader-subscriptions' ), basePath = context.path; titleActions.setTitle( i18n.translate( 'Notifications', { textOnly: true } ) ); analytics.ga.recordPageView( basePath, ANALYTICS_PAGE_TITLE + ' > Notifications > Comments on other sites' ); renderWithReduxStore( React.createElement( NotificationSubscriptions, { userSettings: userSettings, path: context.path } ), document.getElementById( 'primary' ), context.store ); } };
src/parser/druid/balance/modules/talents/azeritetraits/DawningSun.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatNumber, formatPercentage } from 'common/format'; import { calculateAzeriteEffects } from 'common/stats'; import HIT_TYPES from 'game/HIT_TYPES'; import Analyzer from 'parser/core/Analyzer'; import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic'; import SpellLink from 'common/SpellLink'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import StatTracker from 'parser/shared/modules/StatTracker'; const debug = false; class DawningSun extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, statTracker: StatTracker, }; /** * Gives you a buff that increases your solar wrath damage by x for 8 seconds * lets track how much damage you gained from it */ bonusDamage = 0; getAbility = spellId => this.abilityTracker.getAbility(spellId); constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.DAWNING_SUN.id); if (!this.active) { return; } this.bonus = this.selectedCombatant.traitsBySpellId[SPELLS.DAWNING_SUN.id] .reduce((total, rank) => { const [ damage ] = calculateAzeriteEffects(SPELLS.DAWNING_SUN.id, rank); debug && this.log(`Rank ${rank}, damage ${damage}`); return total + damage; }, 0); } on_byPlayer_damage(event){ const spellId = event.ability.guid; const versPerc = this.statTracker.currentVersatilityPercentage; let critMod = 1; if(event.hitType === HIT_TYPES.CRIT){ critMod = 2; } if(this.selectedCombatant.hasBuff(SPELLS.DAWNING_SUN_BUFF.id) && spellId === SPELLS.SOLAR_WRATH_MOONKIN.id){ this.bonusDamage += this.bonus * (1 + versPerc) * critMod; } } on_fightend(){ if(debug){ console.log("Bonus damage", this.bonusDamage); console.log(this.getAbility(SPELLS.SOLAR_WRATH_MOONKIN.id).damageEffective); } } statistic() { return ( <AzeritePowerStatistic size="flexible" tooltip={( <> Added a total of {formatNumber(this.bonusDamage)} to your Solar Wraths.<br /> </> )} > <div className="pad"> <label><SpellLink id={SPELLS.DAWNING_SUN.id} /></label> <div className="value" style={{ marginTop: 15 }}> {formatPercentage(this.bonusDamage / this.getAbility(SPELLS.SOLAR_WRATH_MOONKIN.id).damageEffective)}% <small>of Solar Wrath Damage</small> </div> </div> </AzeritePowerStatistic> ); } } export default DawningSun;
techCurriculum/ui/solutions/2.6/src/components/Card.js
AnxChow/EngineeringEssentials-group
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; import User from './User'; import Message from './Message'; function Card() { return ( <div className='card'> <User /> <div className='card-main'> <Message /> </div> </div> ); } export default Card;
examples/custom-validation/app.js
sdemjanenko/formsy-react
import React from 'react'; import ReactDOM from 'react-dom'; import Formsy from 'formsy-react'; import MyInput from './../components/Input'; const currentYear = new Date().getFullYear(); const validators = { time: { regexp: /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/, message: 'Not valid time' }, decimal: { regexp: /(^\d*\.?\d*[0-9]+\d*$)|(^[0-9]+\d*\.\d*$)/, message: 'Please type decimal value' }, binary: { regexp: /^([0-1])*$/, message: '10101000' } }; Formsy.addValidationRule('isYearOfBirth', (values, value) => { value = parseInt(value); if (typeof value !== 'number') { return false; } return value < currentYear && value > currentYear - 130; }); const App = React.createClass({ submit(data) { alert(JSON.stringify(data, null, 4)); }, render() { return ( <Formsy.Form onSubmit={this.submit} className="custom-validation"> <MyInput name="year" title="Year of Birth" type="number" validations="isYearOfBirth" validationError="Please type your year of birth" /> <DynamicInput name="dynamic" title="..." /> <button type="submit">Submit</button> </Formsy.Form> ); } }); const DynamicInput = React.createClass({ mixins: [Formsy.Mixin], getInitialState() { return { validationType: 'time' }; }, changeValue(event) { this.setValue(event.currentTarget.value); }, changeValidation(validationType) { this.setState({ validationType: validationType }); this.setValue(this.getValue()); }, validate() { const value = this.getValue(); console.log(value, this.state.validationType); return value ? validators[this.state.validationType].regexp.test(value) : true; }, getCustomErrorMessage() { return this.showError() ? validators[this.state.validationType].message : ''; }, render() { const className = 'form-group' + (this.props.className || ' ') + (this.showRequired() ? 'required' : this.showError() ? 'error' : null); const errorMessage = this.getCustomErrorMessage(); return ( <div className={className}> <label htmlFor={this.props.name}>{this.props.title}</label> <input type='text' name={this.props.name} onChange={this.changeValue} value={this.getValue()}/> <span className='validation-error'>{errorMessage}</span> <Validations validationType={this.state.validationType} changeValidation={this.changeValidation}/> </div> ); } }); const Validations = React.createClass({ changeValidation(e) { this.props.changeValidation(e.target.value); }, render() { const { validationType } = this.props; return ( <fieldset onChange={this.changeValidation}> <legend>Validation Type</legend> <div> <input name='validationType' type='radio' value='time' defaultChecked={validationType === 'time'}/>Time </div> <div> <input name='validationType' type='radio' value='decimal' defaultChecked={validationType === 'decimal'}/>Decimal </div> <div> <input name='validationType' type='radio' value='binary' defaultChecked={validationType === 'binary'}/>Binary </div> </fieldset> ); } }); ReactDOM.render(<App/>, document.getElementById('example'));
src/apps/storefront/src/components/product/index.js
Kevnz/shopkeep
import React from 'react'; class ProductCard extends React.Component { render() { const { product } = this.props; return ( <div className="card" style={{display: 'inline-block'}}> <img src={product.images[0].thumbnail} alt="" className="section media" /> <div className="section darker"><h3>{product.name}</h3></div> <div className="section double-padded"><p>{product.description}</p></div> </div> ); } } export default ProductCard;
frontend/src/AddMovie/ImportMovie/SelectFolder/ImportMovieSelectFolder.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Alert from 'Components/Alert'; import FieldSet from 'Components/FieldSet'; import FileBrowserModal from 'Components/FileBrowser/FileBrowserModal'; import Icon from 'Components/Icon'; import Button from 'Components/Link/Button'; import LoadingIndicator from 'Components/Loading/LoadingIndicator'; import PageContent from 'Components/Page/PageContent'; import PageContentBody from 'Components/Page/PageContentBody'; import Table from 'Components/Table/Table'; import TableBody from 'Components/Table/TableBody'; import { icons, kinds, sizes } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import ImportMovieRootFolderRowConnector from './ImportMovieRootFolderRowConnector'; import styles from './ImportMovieSelectFolder.css'; const rootFolderColumns = [ { name: 'path', label: translate('Path'), isVisible: true }, { name: 'freeSpace', label: translate('FreeSpace'), isVisible: true }, { name: 'unmappedFolders', label: translate('UnmappedFolders'), isVisible: true }, { name: 'actions', isVisible: true } ]; class ImportMovieSelectFolder extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isAddNewRootFolderModalOpen: false }; } // // Lifecycle onAddNewRootFolderPress = () => { this.setState({ isAddNewRootFolderModalOpen: true }); } onNewRootFolderSelect = ({ value }) => { this.props.onNewRootFolderSelect(value); } onAddRootFolderModalClose = () => { this.setState({ isAddNewRootFolderModalOpen: false }); } // // Render render() { const { isWindows, isFetching, isPopulated, isSaving, error, saveError, items } = this.props; const hasRootFolders = items.length > 0; return ( <PageContent title={translate('ImportMovies')}> <PageContentBody> { isFetching && !isPopulated ? <LoadingIndicator /> : null } { !isFetching && error ? <div> {translate('UnableToLoadRootFolders')} </div> : null } { !error && isPopulated && <div> <div className={styles.header}> {translate('ImportHeader')} </div> <div className={styles.tips}> {translate('ImportTipsMessage')} <ul> <li className={styles.tip} dangerouslySetInnerHTML={{ __html: translate('ImportIncludeQuality', ['<code>movie.2008.bluray.mkv</code>']) }} /> <li className={styles.tip} dangerouslySetInnerHTML={{ __html: translate('ImportRootPath', [`<code>${isWindows ? 'C:\\movies' : '/movies'}</code>`, `<code>${isWindows ? 'C:\\movies\\the matrix' : '/movies/the matrix'}</code>`]) }} /> <li className={styles.tip}>{translate('ImportNotForDownloads')}</li> </ul> </div> { hasRootFolders ? <div className={styles.recentFolders}> <FieldSet legend={translate('RecentFolders')}> <Table columns={rootFolderColumns} > <TableBody> { items.map((rootFolder) => { return ( <ImportMovieRootFolderRowConnector key={rootFolder.id} id={rootFolder.id} path={rootFolder.path} freeSpace={rootFolder.freeSpace} unmappedFolders={rootFolder.unmappedFolders} /> ); }) } </TableBody> </Table> </FieldSet> </div> : null } { !isSaving && saveError ? <Alert className={styles.addErrorAlert} kind={kinds.DANGER} > {translate('UnableToAddRootFolder')} <ul> { saveError.responseJSON.map((e, index) => { return ( <li key={index}> {e.errorMessage} </li> ); }) } </ul> </Alert> : null } <div className={hasRootFolders ? undefined : styles.startImport}> <Button kind={kinds.PRIMARY} size={sizes.LARGE} onPress={this.onAddNewRootFolderPress} > <Icon className={styles.importButtonIcon} name={icons.DRIVE} /> { hasRootFolders ? translate('ChooseAnotherFolder') : translate('StartImport') } </Button> </div> <FileBrowserModal isOpen={this.state.isAddNewRootFolderModalOpen} name="rootFolderPath" value="" onChange={this.onNewRootFolderSelect} onModalClose={this.onAddRootFolderModalClose} /> </div> } </PageContentBody> </PageContent> ); } } ImportMovieSelectFolder.propTypes = { isWindows: PropTypes.bool.isRequired, isFetching: PropTypes.bool.isRequired, isPopulated: PropTypes.bool.isRequired, isSaving: PropTypes.bool.isRequired, error: PropTypes.object, saveError: PropTypes.object, items: PropTypes.arrayOf(PropTypes.object).isRequired, onNewRootFolderSelect: PropTypes.func.isRequired, onDeleteRootFolderPress: PropTypes.func.isRequired }; export default ImportMovieSelectFolder;
app/pages/serviceDetailPage.js
shiyunjie/scs
/** * Created by shiyunjie on 16/12/6. */ import React, { Component } from 'react'; import { StyleSheet, Text, View, Platform, TouchableOpacity, ScrollView, TextInput, Linking, NativeAppEventEmitter, Alert, } from 'react-native'; import UploadPage from './uploadPage' import LogisticsPage from './logisticsPage' import LoginPage from './loginPage' import PayPage from './payPage' import constants from '../constants/constant' import navigatorStyle from '../styles/navigatorStyle' //navigationBar样式 import Icon from 'react-native-vector-icons/Ionicons' import AppEventListenerEnhance from 'react-native-smart-app-event-listener-enhance' import LoadingSpinnerOverlay from 'react-native-smart-loading-spinner-overlay' import {getDeviceID,getToken} from '../lib/User' import XhrEnhance from '../lib/XhrEnhance' //http import Toast from 'react-native-smart-toast' import ProgressView from '../components/modalProgress' import ImageZoomModal from '../components/ImageZoomModal' import ShowPhotoView from '../components/showPhotoView' //import ServicePhotoPage from './servicePhotoPage' import OrderPhotoPage from './orderPhotoPage' let disable = false let service_id class ServiceDetail extends Component { // 构造 constructor(props) { super(props); // 初始状态 this.state = { showProgress: true,//显示加载 showReload: false,//显示加载更多 showDialog: false,//显示确认框 service_no: '',// 服务单号 order_status_name: '',// 服务单状态名称 order_status: '',// 服务单状态 remark: '',// 备注 trade_terms: '',// 贸易条款 country_name: '',// 起运国 destination_name: '',// 目的国 logistics_status_name: '',// 物流状态名称 time_name: '',// 接单时间 id: this.props.id,// 服务单id import_clearance: '',// 进口清关,0否,1是 international_logistics: '',// 国际物流,0否,1是 export_country_land: '',// 出口国陆运,0否,1是 booking_service: '',// 订舱服务,0海运,1空运 domestic_logistics: '',// 国内物流,0否,1是 credit_letter: '',// 信用证0否,1是 pay_type:'',//支付方式 client_name: '',// 委托人 client_phone: '',// 联系电话 commission_content: '',// 委托内容 ship_company_code: '',// 船公司代码 ship_company_name: '',// 船公司名称 pot_cd: '', //申报口岸 ship_name_english: '',// 英文船名 voyage: '',// 航次 bill_num: '',// 提单号 destination_port_name: '',// 目的港 box_quantity_information: '',// 箱型数量信息 suitcase_yard: '',// 提箱堆场 packing_place: '',// 装箱地点 number: '',// 件数 weight: '',// 毛重 volume: '',// 体积 contract_number: '',// 合同号 billing_number: '',// 发票号 consignee_name: '',// 收货人 consignor_name: '',// 发货人 photoList: [] } service_id = this.props.id this.firstFetch = true; } componentDidMount() { setTimeout(()=>disable = true, 1000) } componentWillMount() { NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper) let currentRoute = this.props.navigator.navigationContext.currentRoute this.addAppEventListener( this.props.navigator.navigationContext.addListener('willfocus', (event) => { //console.log(`OrderDetail willfocus...`) //console.log(`currentRoute`, currentRoute) //console.log(`event.data.route`, event.data.route) if (currentRoute === event.data.route) { //console.log("OrderDetail willAppear") NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper) setTimeout(()=>disable = true, 1000) } else { //console.log("OrderDetail willDisappear, other willAppear") } // }) ) this.addAppEventListener( NativeAppEventEmitter.addListener('bill_has_be_conform_should_refresh', (event)=> { if (event) { this._fetchData() } }) ) this.addAppEventListener( this.props.navigator.navigationContext.addListener('didfocus', (event) => { //console.log(`payPage didfocus...`) if (event && currentRoute === event.data.route) { //console.log("upload didAppear") if (this.firstFetch) { this._fetchData() this.firstFetch = false; } } else { //console.log("orderPage willDisappear, other willAppear") } }) ) } async _fetchData() { if (!this.firstFetch) { this._modalLoadingSpinnerOverLay.show() } try { let token = await getToken() let deviceID = await getDeviceID() let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.serviceOrderDetail, id: this.state.id, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) //console.log(`_fetch_sendCode options:`, options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } result = JSON.parse(result) //console.log('gunZip:', result) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == -54) { /** * 发送事件去登录 */ AsyncStorage.removeItem('token') AsyncStorage.removeItem('realName') this.props.navigator.push({ title: '用户登录', component: LoginPage, }) disable = false this.setState({ showProgress: false,//显示加载 showReload: true,//显示加载更多 }) return; } if (result.code && result.code == 10) { this.setState({ showProgress: false,//显示加载 showReload: false,//显示加载更多 service_no: result.result.service_no,// 服务单号 order_status_name: result.result.order_status_name,// 服务单状态名称 order_status: result.result.order_status,// 服务单状态 remark: result.result.remark,// 备注 trade_terms: result.result.trade_terms,// 贸易条款 country_name: result.result.country_name,// 起运国 destination_name: result.result.destination_name,// 目的国 logistics_status_name: result.result.logistics_status_name,// 物流状态名称 time_name: result.result.time_name,// 接单时间 import_clearance: result.result.import_clearance,// 进口清关,0否,1是 international_logistics: result.result.international_logistics,// 国际物流,0否,1是 export_country_land: result.result.export_country_land,// 出口国陆运,0否,1是 booking_service: result.result.booking_service,// 订舱服务,0海运,1空运 domestic_logistics: result.result.domestic_logistics,// 国内物流,0否,1是 credit_letter: result.result.credit_letter,// 信用证0否,1是 pay_type:result.result.pay_type,// 支付方式 client_name: result.result.client_name,// 委托人 client_phone: result.result.client_phone,// 联系电话 commission_content: result.result.commission_content,// 委托内容 ship_company_code: result.result.ship_company_code,// 船公司代码 ship_company_name: result.result.ship_company_name,// 船公司名称 pot_cd: result.result.pot_cd,// 申报口岸 ship_name_english: result.result.ship_name_english,// 英文船名 voyage: result.result.voyage,// 航次 bill_num: result.result.bill_num,// 提单号 destination_port_name: result.result.destination_port_name,// 目的港 box_quantity_information: result.result.box_quantity_information,// 箱型数量信息 suitcase_yard: result.result.suitcase_yard,// 提箱堆场 packing_place: result.result.packing_place,// 装箱地点 number: result.result.number,// 件数 weight: result.result.weight,// 毛重 volume: result.result.volume,// 体积 contract_number: result.result.contract_number,// 合同号 billing_number: result.result.billing_number,// 发票号 consignee_name: result.result.consignee_name,// 收货人 consignor_name: result.result.consignor_name,// 发货人 }) this._fetchPhotoList() } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) this.setState({ showProgress: false,//显示加载 showReload: true,//显示加载更多 }) } } catch (error) { //console.log(error) if (this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } this.setState({ showProgress: false,//显示加载 showReload: true,//显示加载更多 }) } finally { if (!this.firstFetch && this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide() } //console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`) //SplashScreen.close(SplashScreen.animationType.scale, 850, 500) } } async _fetch_cancel() { if (this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.show() } try { let token = await getToken() let deviceID = await getDeviceID() let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.serviceOrder_cancelServiceOrder, id: this.state.id, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) //console.log(`_fetch_sendCode options:`, options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) result = JSON.parse(result) //console.log('gunZip:', result) if (this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == -54) { /** * 发送事件去登录 */ AsyncStorage.removeItem('token') AsyncStorage.removeItem('realName') this.props.navigator.push({ title: '用户登录', component: LoginPage, }) disable = false return } if (result.code && result.code == 10) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '取消订单成功' }) setTimeout(()=> { //更改订单状态 NativeAppEventEmitter.emit('serviceDetail_hasCancel_should_resetState', this.state.id) this.props.navigator.pop() }, 1000) } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) } } catch (error) { //console.log(error) if (this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } } finally { if (this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } //console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`) //SplashScreen.close(SplashScreen.animationType.scale, 850, 500) } } async _fetchPhotoList() { //console.log(`fetchData_photoList`) try { let token = await getToken() let deviceID = await getDeviceID() let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.uploadImageList, id: service_id, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) //console.log(`_fetchData options:`, options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } result = JSON.parse(result) //console.log('gunZip:', result) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == 10) { //console.log('token', result.result) //let photoList = this.state.photoList //photoList = photoList.concat(result.result) let photoList = [] for (let data of result.result) { photoList.push( { ...data, isStored: true, uploaded: true, uploading: false, }) } //photoList = photoList.concat(result.result) this.setState({ photoList: photoList }) } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) } } catch (error) { //console.log(error) if (this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } } } async _fetch_photoList_finish() { try { let token = await getToken() let deviceID = await getDeviceID() let fileIds = ''; //服务单 for (let data of this.state.photoList) { fileIds += data.id + ',' } let options = { method: 'post', url: constants.api.service, data: { iType: constants.iType.uploadFinish, id: this.state.id, file_ids: fileIds, deviceId: deviceID, token: token, } } options.data = await this.gZip(options) let resultData = await this.fetch(options) let result = await this.gunZip(resultData) if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } result = JSON.parse(result) //console.log('gunZip:', result) if (this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } if (!result) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '服务器打盹了,稍后再试试吧' }) return } if (result.code && result.code == 10) { //console.log('token', result.result) this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: '保存成功' }) } else { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: result.msg }) } } catch (error) { //console.log(error) if (this._toast) { this._toast.show({ position: Toast.constants.gravity.center, duration: 255, children: error }) } } finally { if (this._modalLoadingSpinnerOverLay) { this._modalLoadingSpinnerOverLay.hide({duration: 0,}) } //console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`) //SplashScreen.close(SplashScreen.animationType.scale, 850, 500) } } /** * <View style={[{height:30,backgroundColor:constants.UIInActiveColor}, this.state.order_status==30||this.state.order_status==80||this.state.order_status==90|| this.state.order_status==100||this.state.order_status==10? {width:0}:{width:StyleSheet.hairlineWidth,}]}/> * @returns {XML} */ render() { return ( <View style={{flex:1}}> {this.state.showProgress || this.state.showReload ? <ProgressView showProgress={this.state.showProgress} showReload={this.state.showReload} fetchData={()=>{ this.setState({ showProgress:true,//显示加载 showReload:false,//显示加载更多 }) this._fetchData() }} /> : <ScrollView style={styles.container} showsVerticalScrollIndicator={false}> <View style={[{marginTop:10,flexDirection:'row',alignItems:'center', paddingLeft:constants.MarginLeftRight,backgroundColor:'white'}]}> <Icon name={'logo-python'} size={constants.IconSize} color={constants.UIActiveColor} /> <View style={[styles.viewItem,{flexDirection:'column'}]}> <View style={{flexDirection:'row'}}> <Text style={[{flex:1},styles.labelText]}>服务单{this.state.order_status_name}</Text> <Text style={[{flex:1,textAlign:'right',paddingRight:constants.MarginLeftRight,}, styles.contentText,{fontSize:12,}]}>{this.state.time_name}</Text> </View> <View style={{flexDirection:'row',marginTop:5,}}> <Text style={[styles.contentText,{flex:1,paddingLeft:0,fontSize:12,},]}>{this.state.service_no}</Text> </View> </View> </View> <View style={[{flex:1,flexDirection:'row',backgroundColor:'white',},]}> {this.state.order_status == 10 ? null : <TouchableOpacity style={[styles.line,{justifyContent:'center',alignItems:'center', paddingTop:10,paddingBottom:10,},{flex:1}]} onPress={()=>{ let type='pay' if(this.state.order_status==20||this.state.order_status==30|| this.state.order_status==70||this.state.order_status==100){ type='show' } if(this.state.order_status!=10){ this.props.navigator.push({ title: '账单', component: PayPage, passProps: { id:this.state.id, pageType:type, order_status: this.state.order_status, } }); disable=false } }}> <Text style={{color:constants.UIActiveColor,fontSize:12,}}>账单</Text> </TouchableOpacity> } {this.state.order_status == 10 || this.state.order_status == 20 || this.state.order_status == 40 || this.state.order_status == 70 ? <TouchableOpacity style={[styles.line,{justifyContent:'center',alignItems:'center', paddingTop:10,paddingBottom:10,},{flex:1,}]} onPress={ ()=>{ //弹窗取消订单 //this.setState({showDialog:true,}) Alert.alert('温馨提醒','确定取消吗?',[ {text:'确定',onPress:()=>this._fetch_cancel()}, {text:'取消',onPress:()=>{}}, ]) } }> <Text style={{color:constants.UIActiveColor,fontSize:12,}}>取消</Text> </TouchableOpacity> : null } <TouchableOpacity style={[styles.line,{flex:1,justifyContent:'center',alignItems:'center',paddingTop:10,paddingBottom:10,}]} onPress={()=>{ //打电话 return Linking.openURL(constants.Tel); }}> <Text style={{color:constants.UIActiveColor,fontSize:12,}}>联系客服</Text> </TouchableOpacity> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>订单详情</Text> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>物流状态</Text> <Text style={[{flex:3,paddingLeft:0,textAlign:'right',fontSize:12, color:constants.UIActiveColor,paddingRight:constants.MarginLeftRight*2,},]} onPress={() => { //查看物流 this.props.navigator.push({ title: '查看物流', component: LogisticsPage, passProps: { service_id:service_id, } }); disable=false }}>{this.state.logistics_status_name != null && this.state.logistics_status_name != '' ? this.state.logistics_status_name + '>' : ''}</Text> </View> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>贸易条款</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.trade_terms}</Text> </View> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>委托人</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.client_name}</Text> </View> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>联系方式</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.client_phone}</Text> </View> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>出发国家</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.country_name}</Text> </View> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>目的国家</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.destination_name}</Text> </View> <View style={{flex:1}}> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}, ]}>上传资料</Text> <ShowPhotoView style={{flex:1,backgroundColor:'white', paddingLeft:constants.MarginLeftRight,paddingRight:constants.MarginLeftRight,}} navigator={this.props.navigator} photoList={this.state.photoList} showUpload={!(this.state.order_status == 30 || this.state.order_status == 80 || this.state.order_status == 90 || this.state.order_status == 100 || !(this.state.photoList && this.state.photoList.length))} UploadPage={UploadPage} /> </View> { this.state.order_status == 30 || this.state.order_status == 80 || this.state.order_status == 90 || this.state.order_status == 100 ? null : <View style={[{flex:1,flexDirection:'row',backgroundColor:'white',},]}> <TouchableOpacity style={[styles.line,{justifyContent:'center',alignItems:'center', paddingTop:10,paddingBottom:10,},{flex:1}]} onPress={()=>{ //this.props.navigator.push({ // title: '上传资料', // component: UploadPage, // passProps: { // id:service_id, // } // }); /*this.props.navigator.push({ title: '服务单资料', component: OrderPhotoPage, passProps: { id:service_id, type:'service' } }); disable=false*/ this._fetch_photoList_finish() } } > <Text style={{color:constants.UIActiveColor,fontSize:12,}}>保存上传</Text> </TouchableOpacity> </View> //上传 } <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>贸易支付</Text> <View style={styles.viewItem}> <Text style={[{flex:1},styles.labelText]}>支付方式</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.pay_type}</Text> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>货代服务</Text> <View style={[styles.viewItem,{flex:1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', paddingLeft: constants.MarginLeftRight, backgroundColor:'white',},]}> <View style={{flex:1}}> <Text style={[{flex:1},styles.labelText]}>服务内容</Text> </View> <View style={{flex:3,marginRight:constants.MarginLeftRight}}> <Text style={[{flex:1},styles.contentText]}>{this.state.import_clearance == 1 ? '进口清关、' : ``} {this.state.international_logistics == 1 ? '国际物流、' : ``} {this.state.export_country_land == 1 ? '出口国陆运、' : ``} {this.state.booking_service == 0 ? '订舱服务海运、' : ``} {this.state.domestic_logistics == 1 ? '国内物流、' : ``}</Text> </View> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>委托内容</Text> <View style={[styles.viewItem,{flex:1,}]}> <Text style={[{height:100},styles.contentText,{paddingLeft:0}]} multiline={true}//多行输入 numberOfLines={8}> {this.state.commission_content} </Text> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>物流信息</Text> <View style={[styles.viewItem,]}> <Text style={[{flex:1},styles.labelText]}>申报口岸</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.pot_cd}</Text> </View> <View style={[styles.viewItem,]}> <Text style={[{flex:1},styles.labelText]}>船公司</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.ship_company_code}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>公司名字</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.ship_company_name}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>英文船名</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.ship_name_english}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>航次</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.voyage}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>提单号</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.bill_num}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>目的港</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.destination_port_name}</Text> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>货物信息</Text> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>箱型数量</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.box_quantity_information}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>提箱堆场</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.suitcase_yard}</Text> </View> <View style={[styles.viewItem,{flex:1,}]}> <Text style={[{flex:1},styles.labelText]}>装箱地点</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.packing_place}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>件数</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.number}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>毛重</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.weight}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>体积</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.volume}</Text> </View> <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12}]}>其他</Text> <View style={[styles.viewItem,{flex:1,}]}> <Text style={[{flex:1},styles.labelText]}>合同号</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.contract_number}</Text> </View> <View style={[styles.viewItem]}> <Text style={[{flex:1},styles.labelText]}>发票号</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.billing_number}</Text> </View> <View style={[styles.viewItem,{flex:1,}]}> <Text style={[{flex:1},styles.labelText]}>收货人</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.consignee_name}</Text> </View> <View style={[styles.viewItem,{flex:1,}]}> <Text style={[{flex:1},styles.labelText]}>发货人</Text> <Text style={[{flex:3},styles.contentText]}>{this.state.consignor_name}</Text> </View> {this.state.order_status == 30 || this.state.order_status == 70 ? <Text style={[styles.contentText,{paddingTop:5,paddingBottom:5,fontSize:12} ]}>拒绝原因</Text> : null } {this.state.order_status == 30 || this.state.order_status == 70 ? <View style={[styles.viewItem,]}> <Text style={[{height:100},styles.contentText]} multiline={true}//多行输入 numberOfLines={8}> {this.state.remark} </Text> </View> : null } </ScrollView>} <ImageZoomModal ref={ component => this._ImageZoomModal = component } /> <Toast ref={ component => this._toast = component } marginTop={64}> </Toast> <LoadingSpinnerOverlay ref={ component => this._modalLoadingSpinnerOverLay = component }/> </View> ); } } export default AppEventListenerEnhance(XhrEnhance(ServiceDetail)) const styles = StyleSheet.create({ container: { flex: 1, marginTop: Platform.OS == 'ios' ? 64 : 56, backgroundColor: constants.UIBackgroundColor, }, viewItem: { flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', paddingLeft: constants.MarginLeftRight, backgroundColor: 'white', paddingTop: 10, paddingBottom: 10, }, line: { //marginLeft: constants.MarginLeftRight, //marginRight: constants.MarginLeftRight, borderTopWidth: StyleSheet.hairlineWidth, borderLeftWidth: StyleSheet.hairlineWidth, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: constants.LineColor, }, labelText: { fontSize: 14, color: constants.LabelColor, }, contentText: { fontSize: 14, color: constants.PointColor, paddingLeft: constants.MarginLeftRight, }, }); import {navigationBar} from '../components/NavigationBarRouteMapper' const navigationBarRouteMapper = { ...navigationBar, RightButton: function (route, navigator, index, navState) { return ( <TouchableOpacity onPress={() => { if(disable){ //查看物流 navigator.push({ title: '查看物流', component: LogisticsPage, passProps: { service_id:service_id, } }); disable=false } }} style={navigatorStyle.navBarRightButton}> <View style={navigatorStyle.navBarLeftButtonAndroid}> <Text style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize:14}]} color={'white'}> 查看物流 </Text> </View> </TouchableOpacity>) }, }; //const navigationBarRouteMapper = { // // LeftButton: function (route, navigator, index, navState) { // if (index === 0) { // return null; // } // // var previousRoute = navState.routeStack[index - 1]; // return ( // <TouchableOpacity // onPress={() => navigator.pop()} // style={navigatorStyle.navBarLeftButton}> // <View style={navigatorStyle.navBarLeftButtonAndroid}> // <Icon // style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize: 20,}]} // name={'ios-arrow-back'} // size={constants.IconSize} // color={'white'}/> // </View> // </TouchableOpacity> // // ); // }, // // RightButton: function (route, navigator, index, navState) { // return ( // <TouchableOpacity // onPress={() => { // //查看物流 // navigator.push({ // title: '查看物流', // component: LogisticsPage, // passProps: { // service_id:service_id, // } // }); // }} // style={navigatorStyle.navBarRightButton}> // <View style={navigatorStyle.navBarLeftButtonAndroid}> // <Text // style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize:14}]} // color={'white'}> // 查看物流 // </Text> // </View> // </TouchableOpacity>) // }, // // Title: function (route, navigator, index, navState) { // return ( // Platform.OS == 'ios' ? // <Text style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText]}> // {route.title} // </Text> : <View style={navigatorStyle.navBarTitleAndroid}> // <Text style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText]}> // {route.title} // </Text> // </View> // ) // }, // //}
examples/enzyme/CheckboxWithLabel.js
bookman25/jest
// Copyright 2004-present Facebook. All Rights Reserved. import React from 'react'; export default class CheckboxWithLabel extends React.Component { state = { isChecked: false, }; onChange = () => { this.setState({isChecked: !this.state.isChecked}); }; render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } }
test/js/release_test/ViroPivotTest.js
viromedia/viro
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import { ViroSceneNavigator, ViroScene, ViroBox, ViroMaterials, ViroNode, ViroOrbitCamera, ViroCamera, ViroAmbientLight, ViroOmniLight, ViroSpotLight, ViroDirectionalLight, ViroImage, ViroVideo, Viro360Image, Viro360Video, ViroFlexView, ViroUtils, ViroText, ViroAnimations, ViroAnimatedComponent, ViroQuad, ViroSkyBox, ViroSphere, Viro3DObject, } from 'react-viro'; var createReactClass = require('create-react-class'); let polarToCartesian = ViroUtils.polarToCartesian; var ReleaseMenu = require("./ReleaseMenu.js"); var ViroPivotTest = createReactClass({ getInitialState() { return { rotationPivot:"Center", scalePivot:"Center", }; }, _getPivotArray(pivotLabel) { if (pivotLabel == "Center") { return [0, 0, 0]; } else if (pivotLabel == "Lower Left") { return [-1, -1, 0]; } else if (pivotLabel == "Lower Right") { return [1, -1, 0]; } else if (pivotLabel == "Upper Right") { return [1, 1, 0]; } else if (pivotLabel == "Upper Left") { return [-1, 1, 0]; } else { return [0, 0, 0]; } }, render: function() { var rotationPivot = this._getPivotArray(this.state.rotationPivot); var scalePivot = this._getPivotArray(this.state.scalePivot); return ( <ViroScene> <ReleaseMenu sceneNavigator={this.props.sceneNavigator}/> <ViroOmniLight position={[0, 0, 0]} color="#ffffff" attenuationStartDistance={40} attenuationEndDistance={50}/> <ViroImage source={require('./res/poi_dot.png')} position={[-1, 0, 0]} transformBehaviors={["billboard"]} onClick={this._showNext} /> <ViroBox width={2} height={2} length={2} position={[0, 0, -6]} rotationPivot={rotationPivot} scalePivot={scalePivot} materials={["boxMaterial"]} animation={{name:"scaleAndRotate", delay:0, loop:true, run:true}} /> <ViroNode position={[0,-4,-3]}> <ViroText style={styles.baseTextTwo} position={[-2, 1, 0]} width={2} height={2} text={"Change Rotation Pivot [Current : " + this.state.rotationPivot + "]"} onClick={this._toggleRotationPivot}/> <ViroText style={styles.baseTextTwo} position={[0, 1, 0]} width={2} height={2} text={"Change Scale Pivot [Current : " + this.state.scalePivot + "]"} onClick={this._toggleScalePivot}/> </ViroNode> </ViroScene> ); }, _showNext() { this.props.sceneNavigator.replace({scene:require('./ViroBoxTest')}); }, _getNextPivot(currentPivot) { if (currentPivot == "Center") { return "Lower Left"; } else if (currentPivot == "Lower Left") { return "Lower Right"; } else if (currentPivot == "Lower Right") { return "Upper Right"; } else if (currentPivot == "Upper Right") { return "Upper Left"; } else { return "Center"; } }, _toggleRotationPivot() { var newPivot = this._getNextPivot(this.state.rotationPivot); this.setState({ rotationPivot:newPivot, }); }, _toggleScalePivot() { var newPivot = this._getNextPivot(this.state.scalePivot); this.setState({ scalePivot:newPivot, }); }, }); ViroAnimations.registerAnimations({ scaleUp:{properties:{scaleX:"+=0.5", scaleY:"+=0.5", scaleZ:"+=0.5"}, duration:1000}, scaleDown:{properties:{scaleX:"-=0.5", scaleY:"-=0.5", scaleZ:"-=0.5"}, duration:1000}, rotate:{properties:{rotateZ:"+=360"}, duration:1000}, scaleAndRotate:[ ["rotate", "scaleUp", "scaleDown"], ], }); var styles = StyleSheet.create({ baseTextTwo: { fontFamily: 'Arial', fontSize: 18, color: '#ffffff', textAlignVertical: 'center', textAlign: 'center', } }); ViroMaterials.createMaterials({ boxMaterial: { shininess : 2.0, lightingModel: "Blinn", diffuseTexture: require('./res/360_waikiki.jpg'), }, }); module.exports = ViroPivotTest;
test/test_helper.js
laniywh/game-of-life
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/index.js
kkrizka/bex
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
packages/react-error-overlay/src/components/NavigationBar.js
christiantinauer/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import { red, redTransparent } from '../styles'; const navigationBarStyle = { marginBottom: '0.5rem', }; const buttonContainerStyle = { marginRight: '1em', }; const _navButtonStyle = { backgroundColor: redTransparent, color: red, border: 'none', borderRadius: '4px', padding: '3px 6px', cursor: 'pointer', }; const leftButtonStyle = { ..._navButtonStyle, borderTopRightRadius: '0px', borderBottomRightRadius: '0px', marginRight: '1px', }; const rightButtonStyle = { ..._navButtonStyle, borderTopLeftRadius: '0px', borderBottomLeftRadius: '0px', }; type Callback = () => void; type NavigationBarPropsType = {| currentError: number, totalErrors: number, previous: Callback, next: Callback, |}; function NavigationBar(props: NavigationBarPropsType) { const { currentError, totalErrors, previous, next } = props; return ( <div style={navigationBarStyle}> <span style={buttonContainerStyle}> <button onClick={previous} style={leftButtonStyle}> ← </button> <button onClick={next} style={rightButtonStyle}> → </button> </span> {`${currentError} of ${totalErrors} errors on the page`} </div> ); } export default NavigationBar;
react/src/Monitor.js
gschrader/ratpack-react-boilerplate
import React from 'react'; import {Card, Col, ProgressBar, Row} from 'react-bootstrap'; import Countdown from 'countdown'; import bytes from 'bytes'; import {useWs} from "./hooks"; const Item = props => ( <Row> <Col md={4}> <strong>{props.label}</strong> </Col> <Col md={8}> {props.value} {props.children} </Col> </Row> ); function Monitor() { const [data, disconnected] = useWs('/api/jvmws', localStorage.getItem('jv_jwt')); if (data && !disconnected) { var usedpct = Math.round((data.used / data.total) * 100); var freepct = Math.round((data.free / data.total) * 100); var gctime = Countdown(0, data.gc).toString(); var gcTimeStr = data.gc + ' ms ' + (gctime ? '(' + gctime + ')' : ''); var cpupct = Math.round(data.cpu * 100); return ( <div className="container"> <h1>Monitor</h1> <Card> <Card.Header>Overview</Card.Header> <Card.Body> <Item label="Uptime" value={Countdown(0, data.uptime).toString()}/> <Item label="GC Time" value={gcTimeStr}/> <Item label="CPU"> <ProgressBar active now={cpupct} label={`${cpupct}%`}/></Item> </Card.Body> </Card> <Card> <Card.Header>Heap</Card.Header> <Card.Body> <Row> <Col md={6}> <Item label="Used" value={bytes(data.used)}/> <Item label="Free" value={bytes(data.free)}/> <Item label="Total" value={bytes(data.total)}/> <Item label="Max" value={bytes(data.max)}/> </Col> </Row> <Row> <Col md={12}> <ProgressBar> <ProgressBar variant="danger" now={usedpct} key={1} label={`${usedpct}%`}/> <ProgressBar variant="success" now={freepct} key={2} label={`${freepct}%`}/> </ProgressBar> </Col> </Row> </Card.Body> </Card> </div>) } else { return React.Fragment; } } export default Monitor;
components/Home/Imprint.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import StaticPage from './StaticPage'; import {FormattedMessage, defineMessages} from 'react-intl'; import setDocumentTitle from '../../actions/setDocumentTitle'; class Imprint extends React.Component { componentDidMount() { this.context.executeAction(setDocumentTitle, { title: this.context.intl.formatMessage({ id: 'imprint.title', defaultMessage: 'Imprint' }) }); } render() { //<FormattedMessage id="accessibility.2.header" defaultMessage="Technologies used in the SlideWiki Platform"/> return ( <StaticPage> <div className="ui container grid" ref="imprint"> <div className="ui row"> <div className="ui content"> <h1 className="ui header" id="main"><FormattedMessage id="imprint.header" defaultMessage="Imprint – also serves as provider identification according to &sect; 5 Telemediengesetz (TMG)"/></h1> <h2><FormattedMessage id="imprint.provider" defaultMessage="Provider"/>:</h2> <p>Technische Informationsbibliothek (TIB)<br/>Welfengarten 1 B, 30167 Hannover<br/><br/>Postfach 6080, 30060 Hannover</p> <h2><FormattedMessage id="imprint.representative" defaultMessage="Authorised Representative"/>:</h2> <p><FormattedMessage id="imprint.representative.text" defaultMessage="Prof. Dr. Sören Auer (Director of TIB)"/> <br/><br/> <FormattedMessage id="imprint.representative.text2" defaultMessage="Technische Informationsbibliothek (TIB) is a foundation of public law of the state of Lower Saxony."/></p> <h3><FormattedMessage id="imprint.authority" defaultMessage="Responsible Supervisory Authority"/>:</h3> <p><FormattedMessage id="imprint.authority.text" defaultMessage="Ministry for Science and Culture of Lower Saxony"/></p> <h3><FormattedMessage id="imprint.contact" defaultMessage="Contact"/>:</h3> <p>Customer service phone:&nbsp;+49 511 762-8989<br/>Central information desk phone: +49 511 762-2268<br/>Fax: +49 511 762-4076<br/>Email: <a href="mailto:information@tib.eu">information@tib.eu</a></p> <h2><FormattedMessage id="imprint.VAT" defaultMessage="VAT (sales tax) registration number"/>:</h2> <p>DE 214931803</p> <h2><FormattedMessage id="imprint.editorialOffice" defaultMessage="Editorial Office"/>:</h2> <p>Dr. Sandra Niemeyer; email: <a href="mailto:sandra.niemeyer@tib.eu">sandra.niemeyer@tib.eu</a></p> <h2><FormattedMessage id="imprint.copyright" defaultMessage="Copyright"/>:</h2> <p><FormattedMessage id="imprint.copyright.text" defaultMessage="The layout of this website is protected under copyright, as are the graphics and all other contents contained in the website."/></p> <h2><FormattedMessage id="imprint.content" defaultMessage="Content Available"/>:</h2> <p><strong><FormattedMessage id="imprint.content.text1" defaultMessage="Provided as-is:"/></strong>&nbsp; <FormattedMessage id="imprint.content.text2" defaultMessage="You acknowledge that we do not make any representations or warranties about the material, data, and information, such as data files, text, computer software, code, music, audio files or other sounds, photographs, videos, or other images (collectively, the “Content”) which you may have access to through your use of SlideWiki. Under no circumstances are we liable in any way for any Content, including, but not limited to: any infringing Content, any errors or omissions in Content, or for any loss or damage of any kind incurred as a result of the use of any Content posted, transmitted, linked from, or otherwise accessible through or made available via SlideWiki. You understand that by using SlideWiki, you may be exposed to Content that is offensive, indecent, or objectionable. You agree that you are solely responsible for your reuse of Content made available through SlideWiki. You should review the terms of the applicable license before you use the Content so that you know what you can and cannot do."/></p> <p><b><FormattedMessage id="imprint.licensing" defaultMessage="Licensing"/>:</b>&nbsp; <FormattedMessage id="imprint.licensing.text" values={{link_licenses: <a href="https://creativecommons.org/licenses/?lang=en"> <FormattedMessage id="imprint.licenses.page" defaultMessage="licenses page"/></a> }} defaultMessage="Content on the SlideWiki OCW Authoring platform is licensed under the Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0), Creative Commons Attribution 4.0 International (CC BY 4.0), or Creative Commons 1.0 Universal Public Domain Dedication (CC0 1.0) – unless otherwise marked. See the CC {link_licenses} for more information."/></p> <p><b><FormattedMessage id="imprint.software" defaultMessage="SlideWiki Software"/>:</b>&nbsp; <FormattedMessage id="imprint.software.text" values={{ link_repository: <a href="http://github.com/slidewiki"> <FormattedMessage id="imprint.repository" defaultMessage="repository"/></a> }} defaultMessage="All of SlideWiki’s software code is Open Source software; please check our code repository."/></p> <h2><FormattedMessage id="imprint.content2" defaultMessage="Content Supplied by You"/></h2> <p><FormattedMessage id="imprint.content2.text" defaultMessage="Your responsibility: You represent, warrant, and agree that no Content posted or otherwise shared by you on or through SlideWiki (“Your Content”), violates or infringes upon the rights of any third party, including copyright, trademark, privacy, publicity, or other personal or proprietary rights, breaches or conflicts with any obligation, such as a confidentiality obligation, or contains libelous, defamatory, or otherwise unlawful material."/></p> <p><FormattedMessage id="imprint.licensing.2" defaultMessage='Licensing Your Content: You retain any copyright that you may have in Your Content. You hereby agree that Your Content: (a) is hereby licensed under the Creative Commons Attribution 4.0 License and may be used under the terms of that license or any later version of a Creative Commons Attribution License, or (b) is in the public domain (such as Content that is not copyrightable or Content you make available under CC0), or \u00A9 if not owned by you, (i) is available under a Creative Commons Attribution 4.0 License or (ii) is a media file that is available under any Creative Commons license.'/></p> <h2><FormattedMessage id="imprint.disclaimer" defaultMessage="Disclaimer"/></h2> <p><FormattedMessage id="imprint.disclaimer.text" defaultMessage="We cannot assume any liability for the content of external pages. Solely the operators of those linked pages are responsible for their content."/></p> </div> </div> </div> </StaticPage> ); } } Imprint.contextTypes = { intl: PropTypes.object.isRequired, executeAction: PropTypes.func.isRequired }; export default Imprint;
src/components/Login/map.js
ascrutae/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import { Input, Icon } from 'antd'; import styles from './index.less'; const map = { UserName: { component: Input, props: { size: 'large', prefix: <Icon type="user" className={styles.prefixIcon} />, placeholder: 'admin', }, rules: [ { required: true, message: 'Please enter username!', }, ], }, Password: { component: Input, props: { size: 'large', prefix: <Icon type="lock" className={styles.prefixIcon} />, type: 'password', placeholder: '888888', }, rules: [ { required: true, message: 'Please enter password!', }, ], }, Mobile: { component: Input, props: { size: 'large', prefix: <Icon type="mobile" className={styles.prefixIcon} />, placeholder: 'mobile number', }, rules: [ { required: true, message: 'Please enter mobile number!', }, { pattern: /^1\d{10}$/, message: 'Wrong mobile number format!', }, ], }, Captcha: { component: Input, props: { size: 'large', prefix: <Icon type="mail" className={styles.prefixIcon} />, placeholder: 'captcha', }, rules: [ { required: true, message: 'Please enter Captcha!', }, ], }, }; export default map;
src/routes/notFound/NotFound.js
cineindustria/site
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NotFound.css'; class NotFound extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>Sorry, the page you were trying to view does not exist.</p> </div> </div> ); } } export default withStyles(s)(NotFound);
webapp/components/PortalPopover/Tooltip.js
raksuns/universal-iraks
import React from 'react'; import Portal from './ReactPortal'; import PositionProvider from './PositionProvider'; import { SIZE, FOREGROUND, BORDER_COLOUR, POSITION, BORDER_WIDTH, USE_FOREGROUND, CLASS_BASE, DEFAULT_ARROW_MARGIN, } from './constants'; const ToolTip = (props) => { const defaults = { classBase: CLASS_BASE, className: '', size: SIZE, offset: DEFAULT_ARROW_MARGIN, foregroundColor: FOREGROUND, color: BORDER_COLOUR, position: props.position || POSITION, borderWidth: BORDER_WIDTH, useForeground: USE_FOREGROUND, }; const options = Object.assign({}, defaults, props.options); const classes = `${options.classBase} ${options.classBase}--${options.position} ${options.className}`; const style = {}; if (props.readonly) { style.cursor = 'default'; } return (<div> <Portal closeOnEsc closeOnOutsideClick isOpen={props.isOpened} onClose={props.onClose} > <PositionProvider position={options.position} label={props.label} id={props.id} arrowSize={options.size} arrowOffset={options.offset} target={props.trigger} options={options} classes={classes} style={style} > {props.children} </PositionProvider> </Portal> </div>); }; ToolTip.propTypes = { isOpened: React.PropTypes.bool, readonly: React.PropTypes.bool, small: React.PropTypes.bool, onClose: React.PropTypes.func, trigger: React.PropTypes.object, id: React.PropTypes.string, children: React.PropTypes.node, label: React.PropTypes.string, position: React.PropTypes.string, size: React.PropTypes.number, options: React.PropTypes.object, }; export default ToolTip;
src/modules/textNodes/layouts/TextNodesLayout/TextNodesEditorLayout.js
CtrHellenicStudies/Commentary
import React from 'react'; import Cookies from 'js-cookie'; import PropTypes from 'prop-types'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; // components import Header from '../../../../components/navigation/Header'; import TextNodesEditorContainer from '../../containers/TextNodesEditorContainer/TextNodesEditorContainer'; // lib import muiTheme from '../../../../lib/muiTheme'; import PageMeta from '../../../../lib/pageMeta'; import userInRole from '../../../../lib/userInRole'; class TextNodesEditorLayout extends React.Component { getChildContext() { return { muiTheme: getMuiTheme(muiTheme) }; } componentWillUpdate() { this.handlePermissions(); } componentWillUnmount() { if (this.timeout) clearTimeout(this.timeout); } handlePermissions() { if (!userInRole(Cookies.get('user'), ['editor', 'admin', 'commenter'])) { this.props.history.push('/'); } } render() { PageMeta.setTitle('Edit Source Text | The Center for Hellenic Studies Commentaries'); return ( <MuiThemeProvider muiTheme={getMuiTheme(muiTheme)}> <div className="chs-layout chs-editor-layout add-comment-layout"> <Header /> <main> <div className="commentary-comments"> <div className="comment-group"> <TextNodesEditorContainer /> </div> </div> </main> </div> </MuiThemeProvider> ); } } TextNodesEditorLayout.childContextTypes = { muiTheme: PropTypes.object.isRequired, }; export default TextNodesEditorLayout;
presentation/examples/fragments/example.js
lemieux/smooch-react-talk
import React, { Component } from 'react'; export class FragmentsExample extends Component { render() { const items = ['item 1', 'item 2', 'item 3']; const fragment = items.map((item, index) => { return <li key={ index }> { item } </li>; }); return ( <ul style={ { textAlign: 'left'} }> { fragment } </ul> ); } }
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch06/06_05/start/src/index.js
yevheniyc/Autodidact
import React from 'react' import { render } from 'react-dom' import './stylesheets/ui.scss' import './stylesheets/index.scss' import { App } from './components/App' import { Whoops404 } from './components/Whoops404' import { Router, Route, hashHistory } from 'react-router' window.React = React render( <Router history={hashHistory}> <Route path="/" component={App}/> <Route path="list-days" component={App}> <Route path=":filter" component={App} /> </Route> <Route path="add-day" component={App} /> <Route path="*" component={Whoops404}/> </Router>, document.getElementById('react-container') )
pages/_document.js
dawnlabs/carbon
import React from 'react' import Document, { Head, Main, NextScript } from 'next/document' export default class extends Document { render() { return ( <React.StrictMode> <html lang="en"> <Head /> <body> <Main /> <NextScript /> </body> </html> </React.StrictMode> ) } }
app/features/contact/InputField.js
Kaniwani/KW-Frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Block, Label, Input, Note, ValidationMessage } from './styles'; const InputField = ({ input, meta, label, placeholder, note }) => ( <Block> <Label htmlFor={input.name}> <span>{label || input.name}</span> <Input id={input.name} type="text" placeholder={placeholder} {...input} /> </Label> {meta.touched && meta.error && <ValidationMessage>{meta.error}</ValidationMessage>} {note && <Note constrain>{note}</Note>} </Block> ); InputField.propTypes = { input: PropTypes.object.isRequired, meta: PropTypes.object.isRequired, label: PropTypes.string.isRequired, placeholder: PropTypes.string, note: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), }; InputField.defaultProps = { note: '', placeholder: '', }; export default InputField;
src/client.js
FamilyPlanerTeam/family-planner
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import deepForceUpdate from 'react-deep-force-update'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import App from './components/App'; import createFetch from './createFetch'; import configureStore from './store/configureStore'; import history from './history'; import { updateMeta } from './DOMUtils'; import router from './router'; /* eslint-disable global-require */ // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, // Universal HTTP client fetch: createFetch({ baseUrl: window.App.apiUrl, }), // Initialize a new Redux store // http://redux.js.org/docs/basics/UsageWithReact.html store: configureStore(window.App.state, { history }), storeSubscription: null, }; // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration const scrollPositionsHistory = {}; if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } let onRenderComplete = function initialRenderComplete() { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); onRenderComplete = function renderComplete(route, location) { document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }; }; const container = document.getElementById('app'); let appInstance; let currentLocation = history.location; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; try { // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve({ ...context, path: location.pathname, query: queryString.parse(location.search), }); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } appInstance = ReactDOM.render( <App context={context}>{route.component}</App>, container, () => onRenderComplete(route, location), ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (action && currentLocation.key === location.key) { window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./router', () => { if (appInstance) { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } onLocationChange(currentLocation); }); }
packages/es-components/src/components/controls/radio-buttons/RadioGroup.js
TWExchangeSolutions/es-components
import React from 'react'; import PropTypes from 'prop-types'; import { noop } from 'lodash'; function RadioGroup({ name, disableAllOptions, selectedValue, children, onChange, ...rest }) { return React.Children.map(children, (child, index) => { const key = `${name}-option-${index + 1}`; const disabled = disableAllOptions || child.props.disabled; const checked = selectedValue === child.props.value; return React.cloneElement(child, { key, name, disabled, checked, onChange, ...rest }); }); } RadioGroup.propTypes = { /** The name of the radio group */ name: PropTypes.string.isRequired, /** Selected option for the radio group */ selectedValue: PropTypes.any, /** Disable all radio buttons */ disableAllOptions: PropTypes.bool, /** Function to change selected value */ onChange: PropTypes.func }; RadioGroup.defaultProps = { selectedValue: undefined, disableAllOptions: false, onChange: noop }; /** @component */ export default RadioGroup;
src/Parser/ElementalShaman/CONFIG.js
mwwscott0/WoWAnalyzer
import React from 'react'; import SPECS from 'common/SPECS'; import SPEC_ANALYSIS_COMPLETENESS from 'common/SPEC_ANALYSIS_COMPLETENESS'; import CombatLogParser from './CombatLogParser'; import CHANGELOG from './CHANGELOG'; export default { spec: SPECS.ELEMENTAL_SHAMAN, maintainer: '@fasib', completeness: SPEC_ANALYSIS_COMPLETENESS.NEEDS_MORE_WORK, // When changing this please make a PR with ONLY this value changed, we will do a review of your analysis to find out of it is complete enough. changelog: CHANGELOG, parser: CombatLogParser, footer: ( <div className="panel fade-in" style={{ margin: '15px auto 30px', maxWidth: 400, textAlign: 'center' }}> <div className="panel-body text-muted"> Based on Guides from <a href="https://www.stormearthandlava.com/">Storm Earth and Lava</a>.<br /> Questions about Elementals? Visit <a href="http://www.discord.me/earthshrine">Earthshrine</a> Discord.<br /> </div> </div> ), };
src/components/ui/WebviewLoader/index.js
GustavoKatel/franz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import injectSheet from 'react-jss'; import FullscreenLoader from '../FullscreenLoader'; import styles from './styles'; export default @observer @injectSheet(styles) class WebviewLoader extends Component { static propTypes = { name: PropTypes.string.isRequired, classes: PropTypes.object.isRequired, } render() { const { classes, name } = this.props; return ( <FullscreenLoader className={classes.component} title={`Loading ${name}`} /> ); } }
examples/forms-material-ui/src/components/forms-create-wizard-generic/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import config from './config'; export default createReactClass({ render: function() { return lore.forms.tweet.create(config); } });