path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
app/components/ToolboxComponent.js
ARMataTeam/ARMata
// @flow import React, { Component } from 'react'; import { Image, Icon } from 'semantic-ui-react'; import { DragSource } from 'react-dnd'; import ImageGenerator from '../resources/imageGenerator'; import styles from './ToolboxComponent.css'; // eslint-disable-line flowtype-errors/show-errors const componentSource = { beginDrag(props) { return { name: props.name, }; }, endDrag(props, monitor) { const dropResult = monitor.getDropResult(); if (dropResult) { try { props.addResource(props.resourceType); } catch (ex) { props.error(ex.toString()); } } }, }; class ToolboxComponent extends Component { props: { addResource: (resourceType: string) => void, // eslint-disable-line react/no-unused-prop-types error: (errorMessage: string) => void, // eslint-disable-line react/no-unused-prop-types resourceType: string } render() { return this.props.connectDragSource(<div><Icon circular className={styles.toolboxIcon} size="big"><Image src={ImageGenerator.findImage(this.props.resourceType)} size="mini" centered /></Icon></div>); // eslint-disable-line react/prop-types } } export default DragSource('Component', componentSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }))(ToolboxComponent);
src/Divider/Divider.js
pradel/material-ui
import React from 'react'; const propTypes = { /** * The css class name of the root element. */ className: React.PropTypes.string, /** * If true, the `Divider` will be indented `72px`. */ inset: React.PropTypes.bool, /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, }; const defaultProps = { inset: false, }; const contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; const Divider = (props, context) => { const { inset, style, ...other, } = props; const {muiTheme} = context; const {prepareStyles} = muiTheme; const styles = { root: { margin: 0, marginTop: -1, marginLeft: inset ? 72 : 0, height: 1, border: 'none', backgroundColor: muiTheme.baseTheme.palette.borderColor, }, }; return ( <hr {...other} style={prepareStyles(Object.assign({}, styles.root, style))} /> ); }; Divider.muiName = 'Divider'; Divider.propTypes = propTypes; Divider.defaultProps = defaultProps; Divider.contextTypes = contextTypes; export default Divider;
src/svg-icons/device/signal-wifi-1-bar-lock.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi1BarLock = (props) => ( <SvgIcon {...props}> <path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/> </SvgIcon> ); DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock); DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock'; DeviceSignalWifi1BarLock.muiName = 'SvgIcon'; export default DeviceSignalWifi1BarLock;
pages/index.js
fmarcos83/mdocs
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Home Page</h1> <p>Coming soon.</p> </div> ); } }
project-the-best/src/index.js
renhongl/Summary
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom'; import { Home } from './component/home'; import { Login } from './component/login'; import 'antd/dist/antd.less'; import './share/style/global.less'; import './share/mr/mr.css'; let loggedIn = window.localStorage.getItem('loggedIn'); class App extends Component{ constructor(props) { super(props); this.state = { loggedIn: true } } login = () => { this.setState({ loggedIn: true }) } logout = () => { this.setState({ loggedIn: false }) } render() { return ( <Router> <div className='home'> <Route exact path='/' component={Home}></Route> {/* <Route exact path="/" render={() => ( this.state.loggedIn ? ( <Redirect to="/home"/> ) : ( <Login login={this.login}/> ) )}/> */} </div> </Router> ) } } ReactDOM.render( <App />, document.getElementById('root') )
client/src/templates/Challenges/components/Challenge-Title.js
pahosler/freecodecamp
import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { children: PropTypes.string, isCompleted: PropTypes.bool }; function ChallengeTitle({ children, isCompleted }) { let icon = null; if (isCompleted) { icon = ( // TODO Use SVG here <i className='ion-checkmark-circled text-primary' title='Completed' /> ); } return ( <h2 className='text-center challenge-title'> {children || 'Happy Coding!'} {icon} </h2> ); } ChallengeTitle.displayName = 'ChallengeTitle'; ChallengeTitle.propTypes = propTypes; export default ChallengeTitle;
src/Parser/Core/CombatLogParser.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ChangelogTab from 'Main/ChangelogTab'; import ChangelogTabTitle from 'Main/ChangelogTabTitle'; import TimelineTab from 'Main/Timeline/TimelineTab'; import { formatNumber, formatPercentage, formatThousands, formatDuration } from 'common/format'; import { findByBossId } from 'Raids'; import ApplyBuffNormalizer from './Normalizers/ApplyBuff'; import CancelledCastsNormalizer from './Normalizers/CancelledCasts'; import Status from './Modules/Status'; import HealingDone from './Modules/HealingDone'; import DamageDone from './Modules/DamageDone'; import DamageTaken from './Modules/DamageTaken'; import DeathTracker from './Modules/DeathTracker'; import Combatants from './Modules/Combatants'; import AbilityTracker from './Modules/AbilityTracker'; import Haste from './Modules/Haste'; import StatTracker from './Modules/StatTracker'; import AlwaysBeCasting from './Modules/AlwaysBeCasting'; import Abilities from './Modules/Abilities'; import CastEfficiency from './Modules/CastEfficiency'; import SpellUsable from './Modules/SpellUsable'; import SpellHistory from './Modules/SpellHistory'; import GlobalCooldown from './Modules/GlobalCooldown'; import Enemies from './Modules/Enemies'; import EnemyInstances from './Modules/EnemyInstances'; import Pets from './Modules/Pets'; import HealEventTracker from './Modules/HealEventTracker'; import ManaValues from './Modules/ManaValues'; import SpellManaCost from './Modules/SpellManaCost'; import Channeling from './Modules/Channeling'; import DistanceMoved from './Modules/Others/DistanceMoved'; import CharacterPanel from './Modules/Features/CharacterPanel'; import StatsDisplay from './Modules/Features/StatsDisplay'; import TalentsDisplay from './Modules/Features/TalentsDisplay'; import Checklist from './Modules/Features/Checklist'; import CritEffectBonus from './Modules/Helpers/CritEffectBonus'; import PrePotion from './Modules/Items/PrePotion'; import LegendaryUpgradeChecker from './Modules/Items/LegendaryUpgradeChecker'; import LegendaryCountChecker from './Modules/Items/LegendaryCountChecker'; import EnchantChecker from './Modules/Items/EnchantChecker'; // Legendaries import PrydazXavaricsMagnumOpus from './Modules/Items/Legion/Legendaries/PrydazXavaricsMagnumOpus'; import VelensFutureSight from './Modules/Items/Legion/Legendaries/VelensFutureSight'; import SephuzsSecret from './Modules/Items/Legion/Legendaries/SephuzsSecret'; import KiljaedensBurningWish from './Modules/Items/Legion/Legendaries/KiljaedensBurningWish'; import ArchimondesHatredReborn from './Modules/Items/Legion/Legendaries/ArchimondesHatredReborn'; import CinidariaTheSymbiote from './Modules/Items/Legion/Legendaries/CinidariaTheSymbiote'; import InsigniaOfTheGrandArmy from './Modules/Items/Legion/Legendaries/InsigniaOfTheGrandArmy'; import AmanthulsVision from './Modules/Items/Legion/Legendaries/AmanthulsVision'; // Dungeons/crafted import DrapeOfShame from './Modules/Items/Legion/DrapeOfShame'; import DarkmoonDeckPromises from './Modules/Items/Legion/DarkmoonDeckPromises'; import DarkmoonDeckImmortality from './Modules/Items/Legion/DarkmoonDeckImmortality'; import AmalgamsSeventhSpine from './Modules/Items/Legion/AmalgamsSeventhSpine'; import GnawedThumbRing from './Modules/Items/Legion/GnawedThumbRing'; import EyeOfCommand from './Modules/Items/Legion/EyeOfCommand'; // The Nighthold (T19) import ErraticMetronome from './Modules/Items/Legion/TheNighthold/ErraticMetronome'; // Tomb of Sargeras (T20) import ArchiveOfFaith from './Modules/Items/Legion/TombOfSargeras/ArchiveOfFaith'; import TarnishedSentinelMedallion from './Modules/Items/Legion/TombOfSargeras/TarnishedSentinelMedallion'; import SeaStarOfTheDepthmother from './Modules/Items/Legion/TombOfSargeras/SeaStarOfTheDepthmother'; import DeceiversGrandDesign from './Modules/Items/Legion/TombOfSargeras/DeceiversGrandDesign'; import BarbaricMindslaver from './Modules/Items/Legion/TombOfSargeras/BarbaricMindslaver'; import CharmOfTheRisingTide from './Modules/Items/Legion/TombOfSargeras/CharmOfTheRisingTide'; import EngineOfEradication from './Modules/Items/Legion/TombOfSargeras/EngineOfEradication'; import InfernalCinders from './Modules/Items/Legion/TombOfSargeras/InfernalCinders'; import SpecterOfBetrayal from './Modules/Items/Legion/TombOfSargeras/SpecterOfBetrayal'; import SpectralThurible from './Modules/Items/Legion/TombOfSargeras/SpectralThurible'; import TerrorFromBelow from './Modules/Items/Legion/TombOfSargeras/TerrorFromBelow'; import TomeOfUnravelingSanity from './Modules/Items/Legion/TombOfSargeras/TomeOfUnravelingSanity'; import UmbralMoonglaives from './Modules/Items/Legion/TombOfSargeras/UmbralMoonglaives'; import VialOfCeaselessToxins from './Modules/Items/Legion/TombOfSargeras/VialOfCeaselessToxins'; // Antorus, the Burning Throne (T21) // Healing import TarratusKeystone from './Modules/Items/Legion/AntorusTheBurningThrone/TarratusKeystone'; import HighFathersMachination from './Modules/Items/Legion/AntorusTheBurningThrone/HighfathersMachination'; import EonarsCompassion from './Modules/Items/Legion/AntorusTheBurningThrone/EonarsCompassion'; import GarothiFeedbackConduit from './Modules/Items/Legion/AntorusTheBurningThrone/GarothiFeedbackConduit'; import CarafeOfSearingLight from './Modules/Items/Legion/AntorusTheBurningThrone/CarafeOfSearingLight'; import IshkarsFelshieldEmitter from './Modules/Items/Legion/AntorusTheBurningThrone/IshkarsFelshieldEmitter'; // DPS import SeepingScourgewing from './Modules/Items/Legion/AntorusTheBurningThrone/SeepingScourgewing'; import GorshalachsLegacy from './Modules/Items/Legion/AntorusTheBurningThrone/GorshalachsLegacy'; import GolgannethsVitality from './Modules/Items/Legion/AntorusTheBurningThrone/GolgannethsVitality'; import ForgefiendsFabricator from './Modules/Items/Legion/AntorusTheBurningThrone/ForgefiendsFabricator'; import KhazgorothsCourage from './Modules/Items/Legion/AntorusTheBurningThrone/KhazgorothsCourage'; import TerminusSignalingBeacon from './Modules/Items/Legion/AntorusTheBurningThrone/TerminusSignalingBeacon'; import PrototypePersonnelDecimator from './Modules/Items/Legion/AntorusTheBurningThrone/PrototypePersonnelDecimator'; import SheathOfAsara from './Modules/Items/Legion/AntorusTheBurningThrone/SheathOfAsara'; import NorgannonsProwess from './Modules/Items/Legion/AntorusTheBurningThrone/NorgannonsProwess'; import AcridCatalystInjector from './Modules/Items/Legion/AntorusTheBurningThrone/AcridCatalystInjector'; import ShadowSingedFang from './Modules/Items/Legion/AntorusTheBurningThrone/ShadowSingedFang'; // Tanking import AggramarsConviction from './Modules/Items/Legion/AntorusTheBurningThrone/AggramarsConviction'; // Shared Buffs import Concordance from './Modules/Spells/Concordance'; import VantusRune from './Modules/Spells/VantusRune'; // Netherlight Crucible Traits import DarkSorrows from './Modules/NetherlightCrucibleTraits/DarkSorrows'; import TormentTheWeak from './Modules/NetherlightCrucibleTraits/TormentTheWeak'; import ChaoticDarkness from './Modules/NetherlightCrucibleTraits/ChaoticDarkness'; import Shadowbind from './Modules/NetherlightCrucibleTraits/Shadowbind'; import LightsEmbrace from './Modules/NetherlightCrucibleTraits/LightsEmbrace'; import InfusionOfLight from './Modules/NetherlightCrucibleTraits/InfusionOfLight'; import SecureInTheLight from './Modules/NetherlightCrucibleTraits/SecureInTheLight'; import Shocklight from './Modules/NetherlightCrucibleTraits/Shocklight'; import MurderousIntent from './Modules/NetherlightCrucibleTraits/MurderousIntent'; import MasterOfShadows from './Modules/NetherlightCrucibleTraits/MasterOfShadows'; import LightSpeed from './Modules/NetherlightCrucibleTraits/LightSpeed'; import RefractiveShell from './Modules/NetherlightCrucibleTraits/RefractiveShell'; import NLCTraits from './Modules/NetherlightCrucibleTraits/NLCTraits'; import ParseResults from './ParseResults'; import Analyzer from './Analyzer'; import EventsNormalizer from './EventsNormalizer'; // This prints to console anything that the DI has to do const debugDependencyInjection = false; // This sends every event that occurs to the console, including fabricated events (unlike the Events tab) const debugEvents = false; let _modulesDeprecatedWarningSent = false; class CombatLogParser { static abilitiesAffectedByHealingIncreases = []; static defaultModules = { // Normalizers applyBuffNormalizer: ApplyBuffNormalizer, cancelledCastsNormalizer: CancelledCastsNormalizer, // Analyzers status: Status, healingDone: HealingDone, damageDone: DamageDone, damageTaken: DamageTaken, deathTracker: DeathTracker, combatants: Combatants, enemies: Enemies, enemyInstances: EnemyInstances, pets: Pets, spellManaCost: SpellManaCost, channeling: Channeling, abilityTracker: AbilityTracker, healEventTracker: HealEventTracker, haste: Haste, statTracker: StatTracker, alwaysBeCasting: AlwaysBeCasting, abilities: Abilities, CastEfficiency: CastEfficiency, spellUsable: SpellUsable, spellHistory: SpellHistory, globalCooldown: GlobalCooldown, manaValues: ManaValues, vantusRune: VantusRune, distanceMoved: DistanceMoved, critEffectBonus: CritEffectBonus, characterPanel: CharacterPanel, statsDisplay: StatsDisplay, talentsDisplay: TalentsDisplay, checklist: Checklist, // Items: // Legendaries: prydazXavaricsMagnumOpus: PrydazXavaricsMagnumOpus, velensFutureSight: VelensFutureSight, sephuzsSecret: SephuzsSecret, kiljaedensBurningWish: KiljaedensBurningWish, archimondesHatredReborn: ArchimondesHatredReborn, cinidariaTheSymbiote: CinidariaTheSymbiote, insigniaOfTheGrandArmy: InsigniaOfTheGrandArmy, amanthulsVision: AmanthulsVision, // Epics: drapeOfShame: DrapeOfShame, amalgamsSeventhSpine: AmalgamsSeventhSpine, darkmoonDeckPromises: DarkmoonDeckPromises, darkmoonDeckImmortality: DarkmoonDeckImmortality, prePotion: PrePotion, legendaryUpgradeChecker: LegendaryUpgradeChecker, legendaryCountChecker: LegendaryCountChecker, enchantChecker: EnchantChecker, gnawedThumbRing: GnawedThumbRing, ishkarsFelshieldEmitter: IshkarsFelshieldEmitter, erraticMetronome: ErraticMetronome, eyeOfCommand: EyeOfCommand, // Tomb trinkets: archiveOfFaith: ArchiveOfFaith, barbaricMindslaver: BarbaricMindslaver, charmOfTheRisingTide: CharmOfTheRisingTide, seaStarOfTheDepthmother: SeaStarOfTheDepthmother, deceiversGrandDesign: DeceiversGrandDesign, vialCeaslessToxins: VialOfCeaselessToxins, specterOfBetrayal: SpecterOfBetrayal, engineOfEradication: EngineOfEradication, tarnishedSentinelMedallion: TarnishedSentinelMedallion, spectralThurible: SpectralThurible, terrorFromBelow: TerrorFromBelow, tomeOfUnravelingSanity: TomeOfUnravelingSanity, // T21 Healing Trinkets tarratusKeystone: TarratusKeystone, highfathersMachinations: HighFathersMachination, eonarsCompassion: EonarsCompassion, garothiFeedbackConduit: GarothiFeedbackConduit, carafeOfSearingLight: CarafeOfSearingLight, // T21 DPS Trinkets seepingScourgewing: SeepingScourgewing, gorshalachsLegacy: GorshalachsLegacy, golgannethsVitality: GolgannethsVitality, forgefiendsFabricator: ForgefiendsFabricator, khazgorothsCourage: KhazgorothsCourage, terminusSignalingBeacon: TerminusSignalingBeacon, prototypePersonnelDecimator: PrototypePersonnelDecimator, sheathOfAsara: SheathOfAsara, norgannonsProwess: NorgannonsProwess, acridCatalystInjector: AcridCatalystInjector, shadowSingedFang: ShadowSingedFang, // T21 Tanking Trinkets aggramarsConviction: AggramarsConviction, // Concordance of the Legionfall concordance: Concordance, // Netherlight Crucible Traits darkSorrows: DarkSorrows, tormentTheWeak: TormentTheWeak, chaoticDarkness: ChaoticDarkness, shadowbind: Shadowbind, lightsEmbrace: LightsEmbrace, infusionOfLight: InfusionOfLight, secureInTheLight: SecureInTheLight, shocklight: Shocklight, refractiveShell: RefractiveShell, murderousIntent: MurderousIntent, masterOfShadows: MasterOfShadows, lightSpeed: LightSpeed, nlcTraits: NLCTraits, infernalCinders: InfernalCinders, umbralMoonglaives: UmbralMoonglaives, }; // Override this with spec specific modules when extending static specModules = {}; report = null; player = null; playerPets = null; fight = null; _modules = {}; get modules() { if (!_modulesDeprecatedWarningSent) { console.error('Using `this.owner.modules` is deprecated. You should add the module you want to use as a dependency and use the property that\'s added to your module instead.'); _modulesDeprecatedWarningSent = true; } return this._modules; } get activeModules() { return Object.keys(this._modules) .map(key => this._modules[key]) .filter(module => module.active); } get playerId() { return this.player.id; } _timestamp = null; get currentTimestamp() { return this.finished ? this.fight.end_time : this._timestamp; } get fightDuration() { return this.currentTimestamp - this.fight.start_time; } get finished() { return this._modules.status.finished; } get playersById() { return this.report.friendlies.reduce((obj, player) => { obj[player.id] = player; return obj; }, {}); } constructor(report, player, playerPets, fight) { this.report = report; this.player = player; this.playerPets = playerPets; this.fight = fight; if (fight) { this._timestamp = fight.start_time; this.boss = findByBossId(fight.boss); } else if (process.env.NODE_ENV !== 'test') { throw new Error('fight argument was empty.'); } this.initializeModules({ ...this.constructor.defaultModules, ...this.constructor.specModules, }); } initializeModules(modules) { const failedModules = []; Object.keys(modules).forEach(desiredModuleName => { const moduleConfig = modules[desiredModuleName]; if (!moduleConfig) { return; } let moduleClass; let options; if (moduleConfig instanceof Array) { moduleClass = moduleConfig[0]; options = moduleConfig[1]; } else { moduleClass = moduleConfig; options = null; } const availableDependencies = {}; const missingDependencies = []; if (moduleClass.dependencies) { Object.keys(moduleClass.dependencies).forEach(desiredDependencyName => { const dependencyClass = moduleClass.dependencies[desiredDependencyName]; const dependencyModule = this.findModule(dependencyClass); if (dependencyModule) { availableDependencies[desiredDependencyName] = dependencyModule; } else { missingDependencies.push(dependencyClass); } }); } if (missingDependencies.length === 0) { if (debugDependencyInjection) { if (Object.keys(availableDependencies).length === 0) { console.log('Loading', moduleClass.name); } else { console.log('Loading', moduleClass.name, 'with dependencies:', Object.keys(availableDependencies)); } } // eslint-disable-next-line new-cap const module = new moduleClass(this, availableDependencies, Object.keys(this._modules).length); // We can't set the options via the constructor since a parent constructor can't override the values of a child's class properties. // See https://github.com/Microsoft/TypeScript/issues/6110 for more info if (options) { Object.keys(options).forEach(key => module[key] = options[key]); } this._modules[desiredModuleName] = module; } else { debugDependencyInjection && console.warn(moduleClass.name, 'could not be loaded, missing dependencies:', missingDependencies.map(d => d.name)); failedModules.push(desiredModuleName); } }); if (failedModules.length !== 0) { debugDependencyInjection && console.warn(`${failedModules.length} modules failed to load, trying again:`, failedModules.map(key => modules[key].name)); const newBatch = {}; failedModules.forEach((key) => { newBatch[key] = modules[key]; }); this.initializeModules(newBatch); } } findModule(type) { return Object.keys(this._modules) .map(key => this._modules[key]) .find(module => module instanceof type); } _debugEventHistory = []; initialize(combatants) { this.initializeNormalizers(combatants); this.initializeAnalyzers(combatants); } initializeAnalyzers(combatants) { this.parseEvents(combatants); this.triggerEvent('initialized'); } parseEvents(events) { if (process.env.NODE_ENV === 'development') { this._debugEventHistory = [ ...this._debugEventHistory, ...events, ]; } events.forEach((event) => { if (this.error) { throw new Error(this.error); } this._timestamp = event.timestamp; // Triggering a lot of events here for development pleasure; does this have a significant performance impact? this.triggerEvent(event.type, event); }); } initializeNormalizers(combatants) { this.activeModules .filter(module => module instanceof EventsNormalizer) .sort((a, b) => a.priority - b.priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(module => { if (module.initialize) { module.initialize(combatants); } }); } normalize(events) { this.activeModules .filter(module => module instanceof EventsNormalizer) .sort((a, b) => a.priority - b.priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(module => { if (module.normalize) { events = module.normalize(events); } }); return events; } /** @type {number} The amount of events parsed. This can reliably be used to determine if something should re-render. */ eventCount = 0; _moduleTime = {}; triggerEvent(eventType, event, ...args) { debugEvents && console.log(eventType, event, ...args); Object.keys(this._modules) .filter(key => this._modules[key].active) .filter(key => this._modules[key] instanceof Analyzer) .sort((a, b) => this._modules[a].priority - this._modules[b].priority) // lowest should go first, as `priority = 0` will have highest prio .forEach(key => { const module = this._modules[key]; if (process.env.NODE_ENV === 'development') { const start = +new Date(); module.triggerEvent(eventType, event, ...args); const duration = +new Date() - start; this._moduleTime[key] = this._moduleTime[key] || 0; this._moduleTime[key] += duration; } else { module.triggerEvent(eventType, event, ...args); } }); this.eventCount += 1; } byPlayer(event, playerId = this.player.id) { return (event.sourceID === playerId); } toPlayer(event, playerId = this.player.id) { return (event.targetID === playerId); } byPlayerPet(event) { return this.playerPets.some(pet => pet.id === event.sourceID); } toPlayerPet(event) { return this.playerPets.some(pet => pet.id === event.targetID); } // TODO: Damage taken from LOTM getPercentageOfTotalHealingDone(healingDone) { return healingDone / this._modules.healingDone.total.effective; } formatItemHealingDone(healingDone) { return `${formatPercentage(this.getPercentageOfTotalHealingDone(healingDone))} % / ${formatNumber(healingDone / this.fightDuration * 1000)} HPS`; } formatItemAbsorbDone(absorbDone) { return `${formatNumber(absorbDone)}`; } getPercentageOfTotalDamageDone(damageDone) { return damageDone / this._modules.damageDone.total.effective; } formatItemDamageDone(damageDone) { return `${formatPercentage(this.getPercentageOfTotalDamageDone(damageDone))} % / ${formatNumber(damageDone / this.fightDuration * 1000)} DPS`; } formatManaRestored(manaRestored) { return `${formatThousands(manaRestored)} mana / ${formatThousands(manaRestored / this.fightDuration * 1000 * 5)} MP5`; } formatTimestamp(timestamp, precision = 0) { return formatDuration((timestamp - this.fight.start_time) / 1000, precision); } generateResults() { const results = new ParseResults(); results.tabs = []; results.tabs.push({ title: 'Timeline', url: 'timeline', order: 2, render: () => ( <TimelineTab start={this.fight.start_time} end={this.currentTimestamp >= 0 ? this.currentTimestamp : this.fight.end_time} historyBySpellId={this.modules.spellHistory.historyBySpellId} globalCooldownHistory={this.modules.globalCooldown.history} channelHistory={this.modules.channeling.history} abilities={this.modules.abilities} isAbilityCooldownsAccurate={this.modules.spellUsable.isAccurate} isGlobalCooldownAccurate={this.modules.globalCooldown.isAccurate} /> ), }); results.tabs.push({ title: <ChangelogTabTitle />, url: 'changelog', order: 1000, render: () => <ChangelogTab />, }); Object.keys(this._modules) .filter(key => this._modules[key].active) .sort((a, b) => this._modules[b].priority - this._modules[a].priority) .forEach(key => { const module = this._modules[key]; if (module.statistic) { const statistic = module.statistic(); if (statistic) { results.statistics.push({ statistic, order: module.statisticOrder, }); } } if (module.item) { const item = module.item(); if (item) { results.items.push(item); } } if (module.tab) { const tab = module.tab(); if (tab) { results.tabs.push(tab); } } if (module.suggestions) { module.suggestions(results.suggestions.when); } }); return results; } } export default CombatLogParser;
src/components/NotFoundPage.js
ferryhinardi/swapii_ass
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/components/Loading.js
PsychoLlama/luminary
import { NavigationActions } from 'react-navigation'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import React from 'react'; import * as startupActions from '../actions/startup'; export class Loading extends React.Component { static propTypes = { getAppState: PropTypes.func.isRequired, navigation: PropTypes.shape({ dispatch: PropTypes.func.isRequired, }).isRequired, }; async componentWillMount() { const { payload } = await this.props.getAppState(); const route = payload.serverUrl ? 'Groups' : 'ServerLink'; // Navigate without adding a back button. const navigate = NavigationActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: route })], }); this.props.navigation.dispatch(navigate); } render() { return null; } } const mapDispatchToProps = { getAppState: startupActions.getAppState, }; export default connect(null, mapDispatchToProps)(Loading);
docs/src/MainNav.js
jhernandezme/react-materialize
import React from 'react'; import cx from 'classnames'; import store from './store'; import Icon from '../../src/Icon'; import Collapsible from '../../src/Collapsible'; import CollapsibleItem from '../../src/CollapsibleItem'; let cssComponents = { grid: 'Grid', table: 'Table', }; let jsComponents = { collapsible: 'Collapsible', dropdown: 'Dropdown', media: 'Media', modals: 'Modals', tabs: 'Tabs', }; let components = { badges: 'Badges', buttons: 'Buttons', breadcrumbs: 'Breadcrumbs', cards: 'Cards', chips: 'Chips', collections: 'Collections', footer: 'Footer', forms: 'Forms', navbar: 'Navbar', pagination: 'Pagination', preloader: 'Preloader', }; let keys = Object.keys(jsComponents) .concat(Object.keys(cssComponents)) .concat(Object.keys(components)); class Search extends React.Component { constructor(props) { super(props); this.state = {results: [], focused: false}; this.search = this.search.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); } handleFocus() { this.setState({focused: true}); } handleBlur() { this.setState({focused: false}); } search() { let input = new RegExp(this.refs.search.value, 'i'); let results = []; if (input !== '') { keys.forEach(key => { if (input.test(key)) results.push(key); }); this.setState({results: results}); } } capitalize(path) { return path[0].toUpperCase() + path.substr(1); } render() { let classes = { 'search-wrapper': true, card: true, }; classes.focused = this.state.focused; return ( <li className='search'> <div className={cx(classes)}> <input id='search' ref='search' onChange={this.search} onFocus={this.handleFocus} onBlur={this.handleBlur}></input> <Icon>search</Icon> <div className="search-results"> {this.state.results.map(key => { let path = `/${key}.html`; return <a href={path} key={path}>{this.capitalize(key)}</a>; })} </div> </div> </li> ); } } class MainNav extends React.Component { constructor(props) { super(props); this.state = {title: ''}; this.onChange = this.onChange.bind(this); } componentDidMount() { store.on('component', this.onChange); $(".button-collapse").sideNav({edge: 'left'}); } componentWillUnmount() { store.removeListener('component', this.onChange); } onChange(component) { this.setState({ title: component }); } render() { let {location} = this.props; location = location.substr(1).replace(/\.html/, ''); return ( <header> <nav className="top-nav"> <div className="container" > <div className="nav-wrapper"> <a className="page-title"> { this.state.title } </a> </div> </div> </nav> <div className='container'> <a href='#' data-activates='nav-mobile' className='button-collapse top-nav full hide-on-large-only'> <i className='mdi-navigation-menu'/> </a> </div> <ul id='nav-mobile' className='side-nav fixed'> <li className='logo'> <a className='brand-logo' title='React Materialize' id='logo-container' href="https://react-materialize.github.io" > <img src="assets/react-materialize-logo.svg" alt="React Materialize"/> </a> </li> <Search /> <li className="bold"> <a className="waves-effect waves-teal" href="getting-started.html"> Getting started </a> </li> <li className="no-padding" > <Collapsible> <CollapsibleItem header="CSS" expanded={!!~Object.keys(cssComponents).indexOf(location)} className="bold"> <ul> {Object.keys(cssComponents).map(path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}>{cssComponents[path]}</a> </li> ); })} </ul> </CollapsibleItem> <CollapsibleItem header="Components" expanded={!!~Object.keys(components).indexOf(location)} className="bold"> <ul> {Object.keys(components).map( path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}> {components[path]} </a> </li> ); })} </ul> </CollapsibleItem> <CollapsibleItem header="JavaScript" expanded={!!~Object.keys(jsComponents).indexOf(location)} className="bold"> <ul> {Object.keys(jsComponents).map( path => { let href = path + '.html'; let hrefClasses = { active: location === path, }; return ( <li key={path} className={cx(hrefClasses)}> <a href={href}>{jsComponents[path]}</a> </li> ); })} </ul> </CollapsibleItem> </Collapsible> </li> </ul> </header> ); } } export default MainNav;
src/icons/FiberNewIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FiberNewIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M40 8H8c-2.21 0-3.98 1.79-3.98 4L4 36c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V12c0-2.21-1.79-4-4-4zM17 30h-2.4l-5.1-7v7H7V18h2.5l5 7v-7H17v12zm10-9.49h-5v2.24h5v2.51h-5v2.23h5V30h-8V18h8v2.51zM41 28c0 1.1-.9 2-2 2h-8c-1.1 0-2-.9-2-2V18h2.5v9.01h2.25v-7.02h2.5v7.02h2.25V18H41v10z"/></svg>;} };
app/javascript/mastodon/features/ui/components/column_link.js
lynlynlynx/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import Icon from 'mastodon/components/icon'; const ColumnLink = ({ icon, text, to, href, method, badge }) => { const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null; if (href) { return ( <a href={href} className='column-link' data-method={method}> <Icon id={icon} fixedWidth className='column-link__icon' /> {text} {badgeElement} </a> ); } else { return ( <Link to={to} className='column-link'> <Icon id={icon} fixedWidth className='column-link__icon' /> {text} {badgeElement} </Link> ); } }; ColumnLink.propTypes = { icon: PropTypes.string.isRequired, text: PropTypes.string.isRequired, to: PropTypes.string, href: PropTypes.string, method: PropTypes.string, badge: PropTypes.node, }; export default ColumnLink;
frontend/src/containers/CreateTarget.js
dionyziz/rupture
import React from 'react'; import { ModalHeader, ModalTitle, ModalClose, ModalBody, ModalFooter } from 'react-modal-bootstrap'; import { Form } from 'react-bootstrap'; import axios from 'axios'; export default class CreateTarget extends React.Component { handleSubmit = (event) => { let method; if (this.refs.method1.checked) { method = parseInt(this.refs.method1.value, 10); } else { method = parseInt(this.refs.method2.value, 10); } event.preventDefault(); axios.post('/breach/target', { name: this.refs.name.value, endpoint: this.refs.url.value, prefix: this.refs.prefix.value, alphabet: this.refs.secral.value, secretlength: this.refs.length.value, alignmentalphabet: this.refs.alignal.value, recordscardinality: this.refs.card.value, method: method }) .then(res => { let target_name = res.data.target_name; console.log(res); this.props.onUpdate(target_name); }) .catch(error => { console.log(error); }); } render() { return( <div> <ModalHeader> <ModalClose type='button' className='btn btn-default' onClick={ this.props.onClose }>Close</ModalClose> <ModalTitle> Create Target </ModalTitle> </ModalHeader> <ModalBody> <div className='row'> <div className='col-xs-offset-1 col-xs-11'> <Form onSubmit={ this.handleSubmit }> <div className='form-group'> <label htmlFor='name' className='col-xs-5 progressmargin'>Name:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='name'/> </div> </div> <div className='form-group'> <label htmlFor='url' className='col-xs-5 progressmargin'>Endpoint url:</label> <div className='col-xs-6 progressmargin'> <input type='url' className='form-control' ref='url'/> </div> </div> <div className='form-group'> <label htmlFor='prefix' className='col-xs-5 progressmargin'>Known prefix:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='prefix'/> </div> </div> <div className='form-group'> <label htmlFor='length' className='col-xs-5 progressmargin'>Secret length:</label> <div className='col-xs-6 progressmargin'> <input type='number' className='form-control' ref='length'/> </div> </div> <div className='form-group'> <label htmlFor='secral' className='col-xs-5 progressmargin'>Secret Alphabet:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' ref='secral'/> </div> </div> <div className='form-group'> <label htmlFor='alignal' className='col-xs-5 progressmargin'>Alignment Alphabet:</label> <div className='col-xs-6 progressmargin'> <input type='text' className='form-control' placeholder='abcdefghijklmnopqrstuvwxyz' ref='alignal' /> </div> </div> <div className='form-group'> <label htmlFor='card' className='col-xs-5 progressmargin'>Record cardinality:</label> <div className='col-xs-6 progressmargin'> <input type='number' className='form-control' defaultValue='1' ref='card'/> </div> </div> <div className='form-group'> <label htmlFor='methods' className='col-xs-5 progressmargin'>Method:</label> <div className='radio' name='methods'> <label className='col-xs-4 serialmargin'> <input type='radio' name='method' ref='method1' value='1' defaultChecked/>Serial </label> </div> <div className='col-xs-5'></div> <div className='radio'> <label className='col-xs-4 dividemargin'> <input type='radio' name='method' ref='method2' value='2' />Divide &amp; Conquer </label> </div> </div> </Form> </div> </div> </ModalBody> <ModalFooter> <input type='submit' className='btn btn-default' value='Submit' onClick={ (event) => { this.handleSubmit(event); this.props.onClose(); }}> </input> </ModalFooter> </div> ); } }
app/jsx/external_apps/components/Lti2ReregistrationUpdateModal.js
venturehive/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import I18n from 'i18n!external_tools' import React from 'react' import PropTypes from 'prop-types' import Modal from 'react-modal' import store from 'jsx/external_apps/lib/ExternalAppsStore' export default React.createClass({ displayName: 'Lti2ReregistrationUpdateModal', propTypes: { tool: PropTypes.object.isRequired, closeHandler: PropTypes.func, canAddEdit: PropTypes.bool.isRequired }, getInitialState() { return { modalIsOpen: false } }, openModal(e) { e.preventDefault(); this.setState({modalIsOpen: true}); }, closeModal(cb) { if (typeof cb === 'function') { this.setState({modalIsOpen: false}, cb); } else { this.setState({modalIsOpen: false}); } }, acceptUpdate(e) { e.preventDefault(); this.closeModal(() => { store.acceptUpdate(this.props.tool); }); }, dismissUpdate(e) { e.preventDefault(); this.closeModal(() => { store.dismissUpdate(this.props.tool); }); }, render() { return ( <Modal className="ReactModal__Content--canvas ReactModal__Content--mini-modal" overlayClassName="ReactModal__Overlay--canvas" isOpen={this.state.modalIsOpen} onRequestClose={this.closeModal}> <div className="ReactModal__Layout"> <div className="ReactModal__Header"> <div className="ReactModal__Header-Title"> <h4>{I18n.t('Update %{tool}', {tool: this.props.tool.name})}</h4> </div> <div className="ReactModal__Header-Actions"> <button className="Button Button--icon-action" type="button" onClick={this.closeModal}> <i className="icon-x"></i> <span className="screenreader-only">Close</span> </button> </div> </div> <div className="ReactModal__Body"> {I18n.t('Would you like to accept or dismiss this update?')} </div> <div className="ReactModal__Footer"> <div className="ReactModal__Footer-Actions"> <button ref="btnClose" type="button" className="Button" onClick={this.closeModal}>{I18n.t('Close')}</button> <button ref="btnDelete" type="button" className="Button Button--danger" onClick={this.dismissUpdate}>{I18n.t('Dismiss')}</button> <button ref="btnAccept" type="button" className="Button Button--primary" onClick={this.acceptUpdate}>{I18n.t('Accept')}</button> </div> </div> </div> </Modal> ); } });
app/react-icons/fa/exclamation.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaExclamation extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m24.4 27.9v5q0 0.5-0.4 1t-1 0.4h-5.7q-0.6 0-1-0.4t-0.4-1v-5q0-0.6 0.4-1t1-0.5h5.7q0.6 0 1 0.5t0.4 1z m0.7-23.6l-0.6 17.1q0 0.6-0.5 1t-1 0.5h-5.7q-0.6 0-1-0.5t-0.5-1l-0.6-17.1q0-0.6 0.4-1t1-0.4h7.1q0.6 0 1 0.4t0.4 1z"/></g> </IconBase> ); } }
static/js/components/LoginForm.js
wolendranh/movie_radio
import { Router, Link, browserHistory} from 'react-router'; import {render} from 'react-dom'; import React from 'react'; import $ from 'jquery'; import {login} from '../auth.jsx' // import validator from 'validator'; // TODO: replace validator or make it accessible from import statement class LoginForm extends React.Component { // TODO: divide into smaller reusable components(form, field etc.) constructor(props){ super(props); this.state = { username: 'Ваша_Бармаглот_пошта@mail.com', password: 'Ваш Бармаглот пароль', passwordError: false, usernameError: false, loginError: undefined }; } componentWillMount(){ document.body.style.backgroundColor = "white"; } handlePasswordChange = (e) => { this.setState({ passwordError: this.validateField(this.state.password, validator.isLength, 4) ? false: true}); this.setState({password: e.target.value}); } handleUsernameChange = (e) => { this.setState({username: e.target.value}); this.setState({usernameError: this.validateField(this.state.username, validator.isEmail) ? false: true}); } validateField(data, validatorClass, args){ if (typeof(args) !== 'undefined'){ return validatorClass(data, args); }else{ return validatorClass(data); } } loginHasErrors(){ return 'form-group'+((this.state.usernameError) ? ' has-error': ''); } passwordHasErrors(){ return 'form-group'+((this.state.passwordError) ? ' has-error': ''); } handleSubmit = (e) => { e.preventDefault(); if (this.state.passwordError || this.state.usernameError){ return true } $.ajax({ url: this.props.route.url, dataType: 'json', type: 'POST', data: {'username': this.state.username, 'password': this.state.password}, success: function(data) { localStorage.token = data.token; login(this.state.username, this.state.password); browserHistory.push('/admin'); }.bind(this), error: function(xhr, status, err) { // TODO: handle setting correct server side error into UI this.setState({loginError: err.toString()}); console.error(this.props.route.url, status, err.toString()); }.bind(this) }); } render(){ return ( <div className="wrapper"> <form className="form-signin" method="post" role="form" onSubmit={this.handleSubmit}> <h2 className="form-signin-heading text-center">Бармаглот Адмін</h2> <div className={ this.loginHasErrors() }> <input type="text" className="form-control" onChange={this.handleUsernameChange} placeholder={ this.state.username } name="username" id="login" required=""/> { this.state.usernameError ? <label className="control-label" htmlFor="login">Логін повинен бути адресою електронної пошти</label> :null} </div> <div className={ this.passwordHasErrors() }> <input type="password" className="form-control" onChange={this.handlePasswordChange} placeholder={ this.state.password } id="password" name="password" required=""/> { this.state.passwordError ? <label className="control-label" htmlFor="password">Занадто короткий</label> :null } </div> { this.state.loginError ? <div className="form-group has-error'"> <label className="control-label" for="password">{this.state.loginError}</label> </div> :null } <button type="submit" className="btn btn-lg btn-primary btn-block">Увійти</button> </form> </div> ) } }; export default LoginForm;
lib/cli/generators/REACT/template/stories/Button.js
nfl/react-storybook
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import PropTypes from 'prop-types'; import React from 'react'; const buttonStyles = { border: '1px solid #eee', borderRadius: 3, backgroundColor: '#FFFFFF', cursor: 'pointer', fontSize: 15, padding: '3px 10px', margin: 10, }; const Button = ({ children, onClick }) => <button style={buttonStyles} onClick={onClick}> {children} </button>; Button.propTypes = { children: PropTypes.string.isRequired, onClick: PropTypes.func, }; Button.defaultProps = { onClick: () => {}, }; export default Button;
packages/reactor-kitchensink/src/examples/FormFields/URLField/URLField.js
dbuhrman/extjs-reactor
import React from 'react'; import { FormPanel, URLField } from '@extjs/ext-react'; Ext.require('Ext.data.validator.Url'); export default function UrlFieldExample() { return ( <FormPanel shadow> <URLField placeholder="http://www.domain.com" label="URL" width="200" validators="url" /> </FormPanel> ) }
index.android.js
vinicius-ov/Livefy
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class Livefyy extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('Livefyy', () => Livefyy);
test/test_helper.js
antzu/authenticationApp
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/VideoPlayer.js
MozillaDevelopers/playground
import React from 'react'; import PropTypes from 'prop-types'; // components import ModalVideo from 'react-modal-video'; // CSS import '../../node_modules/react-modal-video/scss/modal-video.scss'; // images import play from './img/play.svg'; class VideoPlayer extends React.Component { constructor() { super(); this.state = { isOpen: false, }; } openModal = () => { this.setState({ isOpen: true, }); } render() { return ( <div className="video-player"> <ModalVideo channel="youtube" isOpen={this.state.isOpen} videoId={this.props.videoId} onClose={() => this.setState({ isOpen: false })} /> <span onClick={this.openModal}> <span className="h2 video-player__text">Launch Video Player</span> <img className="video-player__icon" src={play} alt="play icon" /> </span> </div> ); } } VideoPlayer.propTypes = { videoId: PropTypes.string.isRequired, }; export default VideoPlayer;
src/components/Post/Meta/Meta.js
apalhu/website
// @flow strict import React from 'react'; import moment from 'moment'; import styles from './Meta.module.scss'; type Props = { date: string }; const Meta = ({ date }: Props) => ( <div className={styles['meta']}> <p className={styles['meta__date']}>Published {moment(date).format('D MMM YYYY')}</p> </div> ); export default Meta;
senic_hub/setup_app/__tests__/index.ios.js
grunskis/senic-hub
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
react-flux-mui/js/material-ui/src/svg-icons/editor/format-align-center.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatAlignCenter = (props) => ( <SvgIcon {...props}> <path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/> </SvgIcon> ); EditorFormatAlignCenter = pure(EditorFormatAlignCenter); EditorFormatAlignCenter.displayName = 'EditorFormatAlignCenter'; EditorFormatAlignCenter.muiName = 'SvgIcon'; export default EditorFormatAlignCenter;
src/common/SpellIcon.js
hasseboulen/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPELLS from './SPELLS'; import SpellLink from './SpellLink'; import Icon from './Icon'; const SpellIcon = ({ id, noLink, ...others }) => { if (process.env.NODE_ENV === 'development' && !SPELLS[id]) { throw new Error(`Unknown spell: ${id}`); } const spell = SPELLS[id] || { name: 'Spell not recognized', icon: 'inv_misc_questionmark', }; const icon = ( <Icon icon={spell.icon} alt={spell.name} {...others} /> ); if (noLink) { return icon; } return ( <SpellLink id={id}> {icon} </SpellLink> ); }; SpellIcon.propTypes = { id: PropTypes.number.isRequired, noLink: PropTypes.bool, }; export default SpellIcon;
examples/using-wordpress/src/components/styled/layout.js
okcoker/gatsby
import React from 'react'; import styled, { css } from 'styled-components'; import { compute, ifDefined } from '../../utils/hedron'; import * as PR from './propReceivers'; import { Page as HedronPage, Row as HedronRow, Column as HedronColumn } from 'hedron'; import theme from './theme'; const { sizes, color } = theme; /* * Media Queries * xs: < 450 * sm: < 692 * md: < 991 * lg: 992 and beyound */ // const media = { // tablet: (...args) => css` // @media (min-width: 420px) { // ${ css(...args) } // } // ` // } // Iterate through the sizes and create a media template export const media = Object.keys(sizes).reduce((acc, label) => { acc[label] = (...args) => css` @media (max-width: ${sizes[label] / 16}em) { ${css(...args)} } ` return acc }, {}) /* * Grid */ export const Page = styled(HedronPage)` ${props => props.fluid ? 'width: 100%;' : ` margin: 0 auto; max-width: 100%; ${props.width ? `width: ${props.width};` : `width: ${sizes.max};` } ` } `; export const RowHedron = styled(HedronRow)` display: flex; flex-direction: row; flex-wrap: wrap; ${ifDefined('alignContent', 'align-content')} ${ifDefined('alignItems', 'align-items')} ${ifDefined('alignSelf', 'align-self')} ${ifDefined('justifyContent', 'justify-content')} ${ifDefined('order')} `; export const gutter = props => css` padding-right: 40px; padding-left: 40px; ${media.sm` padding-right: 15px; padding-left: 15px; `} `; export const Row = styled(({ gutter, gutterWhite, height, borderBottom, borderTop, borderLeft, borderRight, outline, ...rest }) => <RowHedron {...rest}/> )` ${props => props.gutter && gutter }; ${props => css` background-color: ${props.gutterWhite ? color.white : color.lightGray}`}; ${PR.heightProps}; ${PR.borderProps}; ${PR.outlineProps}; `; export const Column = styled(({ outline, ...rest }) => <HedronColumn {...rest}/>)` display: block; ${props => props.debug ? `background-color: rgba(50, 50, 255, .1); outline: 1px solid #fff;` : '' } box-sizing: border-box; padding: 0; width: 100%; ${compute('xs')} ${compute('sm')} ${compute('md')} ${compute('lg')} ${PR.outlineProps} `;
components/Deck/TranslationPanel/TranslationPanel.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import {connectToStores} from 'fluxible-addons-react'; import {getLanguageName, getLanguageNativeName} from '../../../common'; import {NavLink, navigateAction} from 'fluxible-router'; import translateDeckRevision from '../../../actions/translateDeckRevision.js'; import { Dropdown, Menu, Button, Modal, Popup } from 'semantic-ui-react'; import TranslationStore from '../../../stores/TranslationStore'; import UserProfileStore from '../../../stores/UserProfileStore'; class TranslationPanel extends React.Component { handleLanguageClick(id){ this.context.executeAction(navigateAction, { url: '/deck/'+ id }); } // handleTranslateToClick(event,data){ // //$(document).find('#deckViewPanel').prepend('<div className="ui active dimmer"><div className="ui text loader">Loading</div></div>'); // this.context.executeAction(translateDeckRevision, { // // TODO this is wrong, the second part for a lanugage code is the COUNTRY not the language, so for greek the el_EL is invalid // language: data.value+'_'+data.value.toUpperCase() // }); // this.dropDown.setValue(''); // // // // // } renderAvailable(translation) { if (translation.language !== this.props.TranslationStore.currentLang.language){ let languageName = ''; if(translation.language){ languageName = getLanguageName(translation.language.toLowerCase().substr(0,2)); } if (languageName){ return ( <Dropdown.Item key = {translation.language} onClick={ this.handleLanguageClick.bind(this, translation.deck_id) } //href={''} > {languageName} </Dropdown.Item> ); } } } renderTranslateTo(supported) { return ( {value:supported.code , text: supported.name} ); } render() { let deckLanguage = ''; this.props.TranslationStore.currentLang ? deckLanguage = this.props.TranslationStore.currentLang.language : deckLanguage = 'Undefined'; //console.log(this.props.TranslationStore); let translations = []; let existing_codes = []; if (this.props.TranslationStore.translations){ translations = this.props.TranslationStore.translations; existing_codes = this.props.TranslationStore.translations.map((el) => { return el.language.split('_')[0]; }); } const supported = this.props.TranslationStore.supportedLangs.filter((el) => { return !existing_codes.includes(el.code); }); const user = this.props.UserProfileStore.userid; let divider = (user && translations.length) ? <Dropdown.Divider /> : ''; let languageOptions = supported.map(this.renderTranslateTo, this); // let translate_item = user ? // // <Dropdown text='Translate...' // floating // labeled // button // scrolling // className='icon primary small' // icon='world' // options={languageOptions} // onChange = {this.handleTranslateToClick.bind(this)} // ref = {(dropDown) => {this.dropDown = dropDown;}} // /> // // : ''; let currentLang = deckLanguage ? <span><i className='icon comments'/>{getLanguageName(deckLanguage.toLowerCase().substr(0,2))}</span> : <span>English</span>; return( <span> {translations.length ? ( <Dropdown item trigger={currentLang}> <Dropdown.Menu> { translations.map(this.renderAvailable, this) } </Dropdown.Menu> </Dropdown> ) : ( <span>{currentLang}</span> )} </span> ); } } TranslationPanel.contextTypes = { executeAction: PropTypes.func.isRequired }; TranslationPanel = connectToStores(TranslationPanel, [TranslationStore, UserProfileStore], (context, props) => { return { TranslationStore: context.getStore(TranslationStore).getState(), UserProfileStore: context.getStore(UserProfileStore).getState() }; }); export default TranslationPanel;
src/components/Form/Button.js
u-wave/web
import cx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import MuiButton from '@mui/material/Button'; function Button({ children, className, ...props }) { return ( <MuiButton variant="contained" color="primary" className={cx('Button', className)} type="submit" {...props} > {children} </MuiButton> ); } Button.propTypes = { className: PropTypes.string, children: PropTypes.node, }; export default Button;
src/components/sidebar/SidebarHeader.js
entria/entria-components
import React from 'react'; import { getTheme } from '../Theme'; const SidebarHeader = ({ children }) => <div style={styles().wrapper}> {children} </div>; const styles = () => ({ wrapper: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', height: 100, padding: 20, backgroundColor: getTheme().palette.primary1Color, color: 'white', boxSizing: 'border-box', }, }); export default SidebarHeader;
geonode/contrib/monitoring/frontend/src/components/cels/response-table/index.js
timlinux/geonode
import React from 'react'; import PropTypes from 'prop-types'; import HR from '../../atoms/hr'; import styles from './styles'; class ResponseTable extends React.Component { static propTypes = { average: PropTypes.number, errorNumber: PropTypes.number, max: PropTypes.number, requests: PropTypes.number, } render() { const average = this.props.average ? `${this.props.average} ms` : 'N/A'; const max = this.props.max ? `${this.props.max} ms` : 'N/A'; const requests = this.props.requests || 0; return ( <div style={styles.content}> <h4>Average Response Time {average}</h4> <HR /> <h4>Max Response Time {max}</h4> <HR /> <h4>Total Requests {requests}</h4> <HR /> <h4>Total Errors {this.props.errorNumber}</h4> </div> ); } } export default ResponseTable;
docs/examples/elements/Milestone.js
krebbl/react-svg-canvas
import React from 'react'; import Element from 'react-svg-canvas/Element'; import Text from 'react-svg-canvas/Text'; import Table from 'react-svg-canvas/Table'; import FontIcon from './FontIcon'; export default class Milestone extends Element { type = 'timeline-milestone'; isGroup = true; static defaultProps = Object.assign({}, Element.defaultProps, { selectable: true, rotate: 0, milestones: [], hoverOnBBox: false }); static childrenTypes = { milestones: Text, labelProps: Text, titleProps: Text, contentProps: Text, iconProps: FontIcon }; static defaultDataProps = { height: -260, milestones: [ { text: 'foo' }, { text: 'bar' } ], iconProps: { font: 'FontAwesome', icon: '\uf135' }, labelProps: { text: '2017', width: 100 }, titleProps: { text: 'My Title' }, contentProps: { text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dol' } }; processChange(key, value, trigger) { super.processChange(key, value, trigger); } renderKnobs() { const ret = super.renderKnobs(); ret.shift(); return ret; } handleSizeChange = (ref) => { const textHeight = ref.actualHeight(); if (this.state.textHeight !== textHeight) { this.setState({ textHeight }); } }; handleClick = () => { this.updateProp('labelProps', Object.assign({}, this.props.labelProps, {text: 'Hello World'})); this.dataChanged(); }; renderChildren() { const bigCircleRadius = 24; const smallCircleColor = this.props.color; const clipId = `milestoneClip_${this.props._id}`; return (<g ref={this.handleBBoxRef}> <g transform={`translate(0,${this.props.height + 10})`}> <Text {...this.props.labelProps} movable={false} scalable={false} textAlign="center" fontSize={12} x={-50} fill={smallCircleColor} onSizeChange={this.handleSizeChange} /> <g transform={`translate(0, ${this.state.textHeight || 12})`}> <line x1="0" x2="0" y1={10} y2={100 - bigCircleRadius + 10} stroke="gray" strokeWidth="1" /> <circle r={bigCircleRadius} stroke="gray" strokeWidth="1" cy={100 + 10} fill="transparent" /> <FontIcon {...this.props.iconProps} movable={false} y={100 + 10} size={26} fill={smallCircleColor} /> <line x1="0" x2="0" y1={100 + bigCircleRadius + 10} y2={-this.props.height - (this.state.textHeight || 12)} stroke="gray" strokeWidth="1" /> <circle r="4" fill="gray" cy={10} /> </g> </g> <circle r="13" fill="white" stroke="gray" strokeWidth="1" /> <circle fill={smallCircleColor} r="11" /> <Table y={this.props.height + (12 * 4) + 10} x={40} rowPadding={5}> <Text {...this.props.titleProps} maxWidth={200} movable={false} scalable={false} textAlign="left" fontSize={14} background={this.context.slide.background} /> <Text {...this.props.contentProps} maxWidth={200} movable={false} scalable={false} textAlign="left" fontSize={12} background={this.context.slide.background} /> </Table> </g>); } }
node_modules/react-bootstrap/es/Tooltip.js
nikhil-ahuja/Express-React
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
examples/js/others/mouse-event-table.js
rolandsusans/react-bootstrap-table
/* eslint no-console: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class MouseEventTable extends React.Component { render() { const options = { onMouseLeave: function() { console.log('mouse leave from table'); }, onMouseEnter: function() { console.log('mouse enter to table'); }, onRowMouseOut: function(row, e) { console.log(e); console.log('mouse leave from row ' + row.id); }, onRowMouseOver: function(row, e) { console.log(e); console.log('mouse enter from row ' + row.id); } }; return ( <BootstrapTable data={ products } options={ options }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
packages/material-ui-icons/src/CellWifiSharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M6 22h16V5.97L6 22z" /><path d="M18 9.98L6 22h12V9.98zM3.93 5.93l1.29 1.29c3.19-3.19 8.38-3.19 11.57 0l1.29-1.29c-3.91-3.91-10.25-3.91-14.15 0zm5.14 5.14L11 13l1.93-1.93c-1.07-1.06-2.79-1.06-3.86 0zM6.5 8.5l1.29 1.29c1.77-1.77 4.65-1.77 6.43 0L15.5 8.5c-2.48-2.48-6.52-2.48-9 0z" /></React.Fragment> , 'CellWifiSharp');
src/App.js
azaleas/game-of-live
import React, { Component } from 'react'; import _ from 'lodash'; import './App.css'; const medium = { boardSize: { width: 60, height: 40, }, boardResize: "medium", boardData: {}, cleanBoard: {}, iteratorCounter: 0, running: false, speed: 20, } const GameBoard = (props) => { const width = props.size.width; return( <div className="gameBoardWrapper" style={{width: width * 10 + "px"}} > { props.data.map((el, index) =>{ const rowIndex = index; return( <div key={"r=" + index} className="boardRow" > { el.map((el, index) => { return( <div key={"c=" + index} data-rowIndex={rowIndex} data-columnIndex={index} onClick={props.cellClick} className={"boardCell " + (el === 1 ? "live" : "dead")} > </div> ) }) } </div> ) }) } </div> ); } class App extends Component { constructor(props) { super(props); this.state = medium; } componentWillMount(){ this.dataFirst(this.state); } dataFirst = (data) =>{ let boardData = []; let boardRows = []; const height = data.boardSize.height; const width = data.boardSize.width; for (let h = 0; h < height; h++){ for (let w = 0; w < width; w++){ boardRows.push(0); if(w + 1 === width){ boardData.push(boardRows); boardRows = []; } } if(h+1 === height){ let cleanBoard = _.cloneDeep(boardData) boardData[2][4] = 1; boardData[3][5] = 1; boardData[4][3] = 1; boardData[4][4] = 1; boardData[4][5] = 1; boardData[6][4] = 1; boardData[6][5] = 1; boardData[6][3] = 1; boardData[5][4] = 1; boardData[4][5] = 1; let state = Object.assign({}, data, { boardData, iteratorCounter: data.iteratorCounter+1, cleanBoard, running: true, }); setTimeout(() => { this.setState(state); this.iterator(data.iteratorCounter, data.speed); }, 500); } } } dataIterate = () => { let height = this.state.boardSize.height; let width = this.state.boardSize.width; let currentData = _.cloneDeep(this.state.boardData); let mirrorData = _.cloneDeep(currentData); let alive = false; for (let h = 0; h < height; h++){ let above = h > 0 ? h-1 : height-1; let below = h < height-1 ? h+1 : 0; for (let w = 0; w < width; w++){ let totalNeighborCount = 0; let left = w > 0 ? w-1 : width-1; let right = w < width-1 ? w+1 : 0; let topLeftCell = currentData[above][left]; let topRightCell = currentData[above][right]; let topCenter = currentData[above][w]; let middleLeft = currentData[h][left]; let middleRight = currentData[h][right]; let bottomLeftCell = currentData[below][left]; let bottomRightCell = currentData[below][right]; let bottomCenter = currentData[below][w]; totalNeighborCount += topLeftCell; // top left totalNeighborCount += topCenter; // top center totalNeighborCount += topRightCell; // top right totalNeighborCount += middleLeft; // middle left totalNeighborCount += middleRight; // middle right totalNeighborCount += bottomLeftCell; // bottom left totalNeighborCount += bottomCenter; // bottom center totalNeighborCount += bottomRightCell; // bottom right if(currentData[h][w] === 0){ switch(totalNeighborCount){ case 3: mirrorData[h][w] = 1; alive = true; //cell is dead but has 3 neighbours => cell alive break; default: mirrorData[h][w] = 0; // leave cell dead if its already dead and doesnt have 3 neighbours } } else if(currentData[h][w] === 1){ switch(totalNeighborCount){ case 2: case 3: mirrorData[h][w] = 1; alive = true; // leave cell alive if neighbour count is >=2 or <=3 break; default: mirrorData[h][w] = 0; //if cell is alive but if neighbour count is <= 1 or >=4 => cell dead } } } if(h+1 === height){ if(alive){ let iteratorCounter = this.state.iteratorCounter; this.setState({ boardData: _.cloneDeep(mirrorData), iteratorCounter: iteratorCounter+1, }); this.iterator(this.state.iteratorCounter, this.state.speed); } else{ this.setState({ boardData: _.cloneDeep(mirrorData), iteratorCounter: 0, running: false, }); } } } } iterator = (iteratorCounter, speed) =>{ iteratorCounter = this.state.iteratorCounter; setTimeout(() => { if(this.state.running){ this.dataIterate(); } }, speed); } play = (event) => { if(!this.state.running){ this.setState({ running: true, }); this.iterator(); } } pause = (event) => { if(this.state.running){ this.setState({ running: false, }) } } clear = (event) => { this.setState({ running: false, boardData: _.cloneDeep(this.state.cleanBoard), iteratorCounter: 0, }); } boardResize = (event) => { let boardName = event.target.name; if(this.state.boardResize !== event.target.name){ this.setState({ running: false, boardData: {}, }); } if(boardName === "medium" && this.state.boardResize !== "medium"){ this.dataFirst(medium); } else if(boardName === "small" && this.state.boardResize !== "small"){ const boardSize = { width: 40, height: 20, }; const small = Object.assign({}, medium, { boardSize, boardResize: "small", speed: 50, running: true, }); this.dataFirst(small); } else if(boardName === "big" && this.state.boardResize !== "big"){ const boardSize = { width: 80, height: 60, }; const big = Object.assign({}, medium, { boardSize, boardResize: "big", speed: 15, running: true, }); this.dataFirst(big); } } cellClick = (event) => { let rowIndex = event.target.getAttribute('data-rowIndex'); let columnIndex = event.target.getAttribute('data-columnIndex'); let currentData = this.state.boardData; currentData[rowIndex][columnIndex] = 1; this.setState({ boardData: currentData, }); } render() { return ( <div className="App container"> <h1 className="bg-primary title">Game Of Life with React</h1> <div className="boardControls"> <div className="btn btn-success" onClick={this.play}>Play</div> <div className="btn btn-warning" onClick={this.pause}>Pause</div> <div className="btn btn-danger" onClick={this.clear}>Clear</div> </div> <p><strong>Generation: </strong>{this.state.iteratorCounter}</p> { (this.state.boardData.length) ? ( <GameBoard data={this.state.boardData} size={this.state.boardSize} cellClick={this.cellClick} /> ) : ( <p>Loading...</p> ) } <div className="boardControls"> <a className="btn btn-info" name="small" onClick={this.boardResize}>Small</a> <a className="btn btn-default" name="medium" onClick={this.boardResize}>Medium</a> <a className="btn btn-primary" name="big" onClick={this.boardResize}>Big</a> </div> </div> ); } } export default App;
src/__tests__/components/Bind-test.js
verkstedt/react-amp-components
import React from 'react' import Bind from '../../components/Bind' import Helmet from '../../utils/Helmet' import { renderComponent } from '../test-utils' describe('Bind', () => { it('works', () => { const res = renderComponent( <Bind text="'bind ' + foo"> <div>test</div> </Bind> ) expect(res.toJSON()).toMatchSnapshot() }) it('works with multiple children', () => { const res = renderComponent( <Bind text="'bind ' + foo"> <div>test</div> <p>another test</p> </Bind> ) expect(res.toJSON()).toMatchSnapshot() }) it('works with props with brackets', () => { const props = { '[text]': 'foo' } const res = renderComponent( <Bind {...props} > <p>test</p> </Bind> ) expect(res.toJSON()).toMatchSnapshot() }) it('works with child with children', () => { const res = renderComponent( <Bind className="'bind ' + foo"> <div id="id" className="class"> <p>One</p> <p>Another</p> </div> </Bind> ) expect(res.toJSON()).toMatchSnapshot() }) it('injects the right script tag', () => { renderComponent( <Bind> <p>Just test the script.</p> </Bind> ) Helmet.canUseDOM = false const staticHead = Helmet.renderStatic() expect(staticHead.scriptTags).toMatchSnapshot() }) it('passes down the right props', () => { const props = { '[text]': "'test ' + foo" } const bind = renderComponent( <Bind text="'test ' + foo"> <p>bind me.</p> </Bind> ) expect(bind.toJSON().props).toMatchObject(props) }) })
blueocean-material-icons/src/js/components/svg-icons/av/volume-off.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvVolumeOff = (props) => ( <SvgIcon {...props}> <path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/> </SvgIcon> ); AvVolumeOff.displayName = 'AvVolumeOff'; AvVolumeOff.muiName = 'SvgIcon'; export default AvVolumeOff;
app/src/reducers/users/Users.spec.js
joedunu/react-redux-example
import React from 'react' import UsersReducer, {types} from './Users' describe('UsersReducer', () => { describe('types', () => { test('returns users reducer types', () => { expect(types).toEqual({ CREATE_USER_FAILED: 'USER/CREATE/FAILED', CREATE_USER_REQUESTED: 'USER/CREATE/REQUESTED', CREATE_USER_SUCCEEDED: 'USER/CREATE/SUCCEEDED', DELETE_USER_FAILED: 'USER/DELETE/FAILED', DELETE_USER_REQUESTED: 'USER/DELETE/REQUESTED', DELETE_USER_SUCCEEDED: 'USER/DELETE/SUCCEEDED', EDIT_USER_FAILED: 'USER/EDIT/FAILEQUESTED', EDIT_USER_REQUESTED: 'USER/EDIT/REQUESTED', EDIT_USER_SUCCEEDED: 'USER/EDIT/SUCCEEDED', FETCH_USER_FAILED: 'USER/FETCH/FAILED', FETCH_USER_REQUESTED: 'USER/FETCH/REQUESTED', FETCH_USER_SUCCEEDED: 'USER/FETCH/SUCCEEDED', TOGGLE_USER: 'USER/TOGGLE' }) }) }) describe('reducer', () => { test('handles TOGGLE_USER', () => { expect( UsersReducer(undefined, { type: types.TOGGLE_USER }) ).toEqual([]) }) test('handles CREATE_USER_SUCCEEDED', () => { expect( UsersReducer(undefined, { type: types.CREATE_USER_SUCCEEDED, user: {firstName: 'David'} }) ).toEqual([{firstName: 'David'}]) }) test('handles DELETE_USER_SUCCEEDED', () => { expect( UsersReducer([{firstName: 'David', id: 1}], { type: types.DELETE_USER_SUCCEEDED, id: 1 }) ).toEqual([]) }) }) })
app/components/CategoriesList/CategoryCard.js
vlastoun/picture-uploader-crud
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardActions, CardTitle, CardText } from 'material-ui/Card'; import DeleteButton from './DeleteButton'; import EditButton from './EditButton'; const buttonStyle = { margin: '0.5em', }; const cardStyle = { marginTop: '1em', marginBottom: '1em', }; /* eslint-disable react/prefer-stateless-function */ /* eslint-disable react/jsx-boolean-value */ class CategoryCard extends React.Component { constructor() { super(); this.state = { edit: false, shadow: 1 }; this.onMouseOut = this.onMouseOut.bind(this); this.onMouseOut = this.onMouseOut.bind(this); } onMouseOver = () => { this.setState({ shadow: 3 }); } onMouseOut = () => { this.setState({ shadow: 1 }); } render() { const { item } = this.props; return ( <Card style={cardStyle} zDepth={this.state.shadow} onMouseOver={this.onMouseOver} onFocus={this.onMouseOver} onMouseOut={this.onMouseOut} onBlur={this.onMouseOut} > <CardTitle title={item.name} actAsExpander={true} showExpandableButton={true} /> <CardText expandable={true}> {item.description} </CardText> <CardActions expandable={true}> <EditButton style={buttonStyle} edit={this.props.edit} post={item}> Edit </EditButton> <DeleteButton style={buttonStyle} delete={this.props.delete} post={item} /> </CardActions> </Card> ); } } CategoryCard.propTypes = { delete: PropTypes.func.isRequired, edit: PropTypes.func.isRequired, item: PropTypes.object.isRequired, }; export default CategoryCard;
es6/Radio/RadioButton.js
yurizhang/ishow
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; //import {default as Component} from '../../plugs/index.js'; //提供style, classname方法 import '../Common/css/radio-button.css'; import Radio from './Radio'; var RadioButton = function (_Radio) { _inherits(RadioButton, _Radio); function RadioButton() { _classCallCheck(this, RadioButton); return _possibleConstructorReturn(this, (RadioButton.__proto__ || Object.getPrototypeOf(RadioButton)).apply(this, arguments)); } _createClass(RadioButton, [{ key: 'parent', value: function parent() { return this.context.component; } }, { key: 'size', value: function size() { return this.parent().props.size; } }, { key: 'isDisabled', value: function isDisabled() { return this.props.disabled || this.parent().props.disabled; } }, { key: 'activeStyle', value: function activeStyle() { return { backgroundColor: this.parent().props.fill || '', borderColor: this.parent().props.fill || '', color: this.parent().props.textColor || '' }; } }, { key: 'render', value: function render() { return React.createElement( 'label', { style: this.style(), className: this.className('ishow-radio-button', this.props.size && 'ishow-radio-button--' + this.size(), { 'is-active': this.state.checked }) }, React.createElement('input', { type: 'radio', className: 'ishow-radio-button__orig-radio', checked: this.state.checked, disabled: this.isDisabled(), onChange: this.onChange.bind(this) }), React.createElement( 'span', { className: 'ishow-radio-button__inner', style: this.state.checked ? this.activeStyle() : {} }, this.props.children || this.props.value ) ); } }]); return RadioButton; }(Radio); RadioButton.elementType = 'RadioButton'; export default RadioButton; RadioButton.contextTypes = { component: PropTypes.any }; RadioButton.propTypes = { value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disabled: PropTypes.bool, name: PropTypes.string };
linksa/YTjinfo.js
liuhui219/linksa
import React from 'react'; import { View, StyleSheet, Navigator, TouchableOpacity, TouchableHighlight, Text, ScrollView, ActivityIndicator, InteractionManager, Dimensions, BackAndroid, Image, RefreshControl, ListView, } from 'react-native'; import ScrollableTabView, { DefaultTabBar, } from 'react-native-scrollable-tab-view'; import Token from './Token'; import Icon from 'react-native-vector-icons/Ionicons'; import YTjinfoa from './YTjinfoa'; var array = []; export default class YTjinfo extends React.Component { constructor(props) { super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), id: '', uid:'', datas:[], imgs:[], loaded: false, isLoadMore:false, p:1, isReach:false, isRefreshing:false, isNull:false, sx:false, datda:null, }; } componentDidMount() { //这里获取传递过来的参数: name array = []; aa=[]; this.setState({datda:data.data.domain}) this.timer = setTimeout( () => {this.fetchData('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '&p='+this.state.p);},800); } componentWillUnmount() { this.timer && clearTimeout(this.timer); } fetchData(url) { var that=this; fetch(url) .then((response) => response.json()) .then((responseData)=>{ if(responseData.data.data != ''){ responseData.data.data.forEach((Data,i) => { key={i} array.push(Data); }) } if(responseData.data.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(responseData.data.count == 0){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isNull:true, }) }else if(array.length > responseData.data.count){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isNull:false, }) } console.log(responseData) }) .catch((error) => { that.setState({ loaded: true, sx:true, isReach:true, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } infos(data){ const { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { this.props.navigator.push({ name: 'YTjinfoa', component: YTjinfoa, params: { data: data, imgs: {uri: this.state.datda.slice(0,-6)+data.img.slice(1)} } }) }) } } render() { if(!this.state.loaded){ return ( <View style={{justifyContent: 'center',alignItems: 'center',height:Dimensions.get('window').height-90,}}> <View style={styles.loading}> <ActivityIndicator color="white"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.loadingTitle}>加载中……</Text> </View> </View> ) } return( <ListView dataSource={this.state.dataSource} renderRow={this.renderMovie.bind(this)} onEndReached={this._onEndReach.bind(this) } onEndReachedThreshold={2} renderFooter={this._renderFooter.bind(this)} refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh.bind(this) } colors={['#ff0000', '#00ff00', '#0000ff','#3ad564']} progressBackgroundColor="#ffffff" /> } /> ) } _ggButton(id){ const { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { this.props.navigator.push({ name: 'Gonggaob', component: Gonggaob, params: { id: id, } }) }) } } renderMovie(data,sectionID: number, rowID: number) { if(this.state.sx){ return( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-sad-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else if(this.state.isNull){ return ( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-folder-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else{ return ( <View style={{paddingBottom:15, justifyContent:'center',alignItems:'center', backgroundColor:'#fff',borderBottomWidth:1, borderColor:'#eee'}}> <TouchableOpacity activeOpacity={0.8} onPress={this.infos.bind(this,data)} style={{justifyContent:'center',alignItems:'center', }}> <View style={{flexDirection:'row',paddingTop:15,}}> <View style={{marginLeft:15,marginRight:15,width: 40, height: 40,borderRadius:20,backgroundColor:'#ccc',alignItems:'center', justifyContent:'center'}}> <Image source={require('./imgs/ren.png')} style={{width: 20, height: 20, }} /> </View> <View style={{flex:1,flexDirection:'column',}}> <View style={{flexDirection:'row',justifyContent:'space-between'}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:14,}}>{data.userid}</Text> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#999',paddingRight:15,}}>{data.time}</Text> </View> <View style={{ borderRadius:3,}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{flexWrap:'wrap',marginTop:5,fontSize:14, paddingRight:15,}}>{data.address}</Text> </View> </View> </View> </TouchableOpacity> </View> ) } } _renderFooter() { if(this.state.isLoadMore){ return ( <View style={styles.footer}> <ActivityIndicator color="#4385f4"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.footerTitle}>正在加载更多……</Text> </View> ) } } // 下拉刷新 _onRefresh() { this.setState({ isRefreshing:true, isReach:false, isLoadMore:false, p:1, }) var that=this fetch('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '') .then((response) => response.json()) .then(function (result) { array=[]; array.length = 0; if(result.data.data != ''){ result.data.data.forEach((Data,i) => { key={i} array.push(Data); }) } if(result.data.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(result.data.count == 0){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isRefreshing:false, isReach:true, isNull:true, }) }else if(array.length > result.data.count){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isRefreshing:false, isNull:false, }) } console.log(result) }) .catch((error) => { that.setState({ loaded: true, sx:true, isReach:true, isRefreshing:false, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } _onEndReach() { if(!this.state.isReach){ this.setState({ isLoadMore:true, p:this.state.p+1, }) InteractionManager.runAfterInteractions(() => { this.fetchData('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '&p='+this.state.p); }) } } } const styles = StyleSheet.create({ tabView: { flex: 1, flexDirection: 'column', backgroundColor:'#fafafa', }, card: { height:45, backgroundColor:'#4385f4', flexDirection:'row' }, loading: { backgroundColor: 'gray', height: 80, width: 100, borderRadius: 10, justifyContent: 'center', alignItems: 'center', }, loadingTitle: { marginTop: 10, fontSize: 14, color: 'white' }, footer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 40, }, footerTitle: { marginLeft: 10, fontSize: 15, color: 'gray' }, default: { height: 37, borderWidth: 0, borderColor: 'rgba(0,0,0,0.55)', flex: 1, fontSize: 13, }, });
web_src/src/components/App.js
salgum1114/sgoh-blog
import React from 'react'; class App extends React.Component { render(){ return ( <div> <h1>SpringBoot ReactJS Start!!</h1> <h2>SpringBoot ReactJS Start!!</h2> <h3>SpringBoot ReactJS Start!!</h3> </div> ); } } export default App;
src/CollapsibleMixin.js
jontewks/react-bootstrap
import React from 'react'; import TransitionEvents from './utils/TransitionEvents'; import deprecationWarning from './utils/deprecationWarning'; const CollapsibleMixin = { propTypes: { defaultExpanded: React.PropTypes.bool, expanded: React.PropTypes.bool }, getInitialState() { const defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : !!this.props.expanded; return { expanded: defaultExpanded, collapsing: false }; }, componentWillMount() { deprecationWarning('CollapsibleMixin', 'Collapse Component'); }, componentWillUpdate(nextProps, nextState) { let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded; if (willExpanded === this.isExpanded()) { return; } // if the expanded state is being toggled, ensure node has a dimension value // this is needed for the animation to work and needs to be set before // the collapsing class is applied (after collapsing is applied the in class // is removed and the node's dimension will be wrong) let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = '0'; if (!willExpanded) { value = this.getCollapsibleDimensionValue(); } node.style[dimension] = value + 'px'; this._afterWillUpdate(); }, componentDidUpdate(prevProps, prevState) { // check if expanded is being toggled; if so, set collapsing this._checkToggleCollapsing(prevProps, prevState); // check if collapsing was turned on; if so, start animation this._checkStartAnimation(); }, // helps enable test stubs _afterWillUpdate() { }, _checkStartAnimation() { if (!this.state.collapsing) { return; } let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = this.getCollapsibleDimensionValue(); // setting the dimension here starts the transition animation let result; if (this.isExpanded()) { result = value + 'px'; } else { result = '0px'; } node.style[dimension] = result; }, _checkToggleCollapsing(prevProps, prevState) { let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded; let isExpanded = this.isExpanded(); if (wasExpanded !== isExpanded) { if (wasExpanded) { this._handleCollapse(); } else { this._handleExpand(); } } }, _handleExpand() { let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let complete = () => { this._removeEndEventListener(node, complete); // remove dimension value - this ensures the collapsible item can grow // in dimension after initial display (such as an image loading) node.style[dimension] = ''; this.setState({ collapsing:false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, _handleCollapse() { let node = this.getCollapsibleDOMNode(); let complete = () => { this._removeEndEventListener(node, complete); this.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, // helps enable test stubs _addEndEventListener(node, complete) { TransitionEvents.addEndEventListener(node, complete); }, // helps enable test stubs _removeEndEventListener(node, complete) { TransitionEvents.removeEndEventListener(node, complete); }, dimension() { return (typeof this.getCollapsibleDimension === 'function') ? this.getCollapsibleDimension() : 'height'; }, isExpanded() { return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, getCollapsibleClassSet(className) { let classes = {}; if (typeof className === 'string') { className.split(' ').forEach(subClasses => { if (subClasses) { classes[subClasses] = true; } }); } classes.collapsing = this.state.collapsing; classes.collapse = !this.state.collapsing; classes.in = this.isExpanded() && !this.state.collapsing; return classes; } }; export default CollapsibleMixin;
demos/forms-demo/src/components/Menu/SettingsCheckbox.js
bdjnk/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state, props, signal} from 'cerebral/tags' export default connect({ 'field': state`${props`path`}`, 'toggleSelectSettings': signal`app.toggleSelectSettings` }, function SettingsCheckbox ({field, path, toggleSelectSettings}) { const {value} = field return ( <div style={{float: 'left', paddingRight: 10, marginTop: 5}}> <input type={'checkbox'} checked={value ? 'checked' : ''} onChange={(e) => toggleSelectSettings({ field: path, value: !value })} /> {field.description} </div> ) } )
src/renderer/components/channel-switcher.js
r7kamura/retro-twitter-client
import List from './list'; import React from 'react'; import viewEventPublisher from '../singletons/view-event-publisher' export default class ChannelSwitcher extends React.Component { getHomeChannelClassName() { return `account-channel ${this.getHomeChannelSelected() ? ' account-channel-selected' : ''}`; } getHomeChannelSelected() { return this.props.channelId === 'HOME_TIMELINE_CHANNEL'; } getSearchChannelClassName() { return `account-channel ${this.getSearchChannelSelected() ? ' account-channel-selected' : ''}`; } getSearchChannelSelected() { return this.props.channelId === 'SEARCH_CHANNEL'; } onHomeChannelClicked(event) { viewEventPublisher.emit('channel-clicked', 'HOME_TIMELINE_CHANNEL'); } onSearchChannelClicked(event) { viewEventPublisher.emit('channel-clicked', 'SEARCH_CHANNEL'); } render() { return( <div className="channel-switcher"> <div className="account-screen-name"> @{this.props.account.screen_name} </div> <div className="account-section"> <h3 className="account-section-heading"> TIMELINES </h3> <ul> <li className={this.getHomeChannelClassName()} onClick={this.onHomeChannelClicked.bind(this)}> Home </li> <li className={this.getSearchChannelClassName()} onClick={this.onSearchChannelClicked.bind(this)}> Search </li> </ul> </div> <div className="account-section"> <h3 className="account-section-heading"> LISTS </h3> <ul> {this.renderLists()} </ul> </div> </div> ); } renderLists() { return this.props.lists.map((list) => { return <List channelId={this.props.channelId} key={list.id_str} list={list} />; }); } }
src/routes.js
IntellectionStudio/intellection.kz
import {PageContainer as PhenomicPageContainer} from 'phenomic'; import {Route} from 'react-router'; import React from 'react'; import AboutPage from 'layouts/AboutPage'; import ContactPage from 'layouts/ContactPage'; import CoursesPage from 'layouts/CoursesPage'; import ErrorPage from 'layouts/ErrorPage'; import HomePage from 'layouts/HomePage'; import KnowledgePage from 'layouts/KnowledgePage'; import Page from 'layouts/Page'; import StartupsPage from 'layouts/StartupsPage'; import ServicesPage from 'layouts/ServicesPage'; import TopicPage from 'layouts/TopicPage'; import AppContainer from './AppContainer'; const PageContainer = props => ( <PhenomicPageContainer {...props} layouts={{ AboutPage, ContactPage, CoursesPage, ErrorPage, HomePage, KnowledgePage, Page, StartupsPage, ServicesPage, TopicPage, }} /> ); const Routes = ( <Route component={AppContainer}> <Route path="*" component={PageContainer} /> </Route> ); export default Routes;
react/Regular/Regular.js
seekinternational/seek-asia-style-guide
import styles from './Regular.less'; import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export default function Regular({ children, className, ...restProps }) { return ( <span {...restProps} className={classnames(styles.root, className)}> {children} </span> ); } Regular.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string };
src/components/templates/content_body.js
hisarkaya/polinsur
import React from 'react'; const ContentBody = props => { return ( <div className="widget-content nopadding"> {props.children} </div> ); } export default ContentBody;
Rosa_Madeira/Cliente/src/components/catalogo/CatalogoLista.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, ListView, RefreshControl, ScrollView } from 'react-native'; import { Container, Content, Card, CardItem, Text, Button, Icon } from 'native-base'; import { connect } from 'react-redux'; import { fetch_catalogo } from '../../actions'; import CatalogoItem from './CatalogoItem'; import { Actions } from 'react-native-router-flux'; class CatalogoLista extends Component { componentWillMount() { this.props.fetch_catalogo(); this.createDataSource(this.props) // const { carrinhoLista } = this.props; // console.log(this.props); Actions.refresh({rightTitle: 'Carrinho', onRight: () => Actions.carrinho({type:'reset', listCarrinho: this.props.carrinhoLista}), rightButtonTextStyle: { color:'white'} }); } componentWillReceiveProps(nextProps){ this.createDataSource(nextProps) } createDataSource({listCatalogo}) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(listCatalogo); } renderRow(listCatalogo) { return <CatalogoItem catalogoLista={listCatalogo} /> } _onRefresh(){ setTimeout(() => { this.props.fetch_catalogo(); }, 1000); } render(){ return( <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} style={{marginTop: 70}} /> ); } } const mapStateToProps = state => { const listCatalogo = _.map(state.catalogo.catalogoLista, (key, value) => { return { ...key, value }; }); const { refreshing } = state.catalogo; const { carrinhoLista } = state.carrinho; return { listCatalogo, refreshing, carrinhoLista }; } export default connect(mapStateToProps, {fetch_catalogo})(CatalogoLista);
test/specs/elements/Icon/Icon-test.js
Semantic-Org/Semantic-UI-React
import _ from 'lodash' import React from 'react' import Icon from 'src/elements/Icon/Icon' import IconGroup from 'src/elements/Icon/IconGroup' import { SUI } from 'src/lib' import * as common from 'test/specs/commonTests' import { sandbox } from 'test/utils' describe('Icon', () => { common.isConformant(Icon) common.hasSubcomponents(Icon, [IconGroup]) common.implementsCreateMethod(Icon) common.propKeyAndValueToClassName(Icon, 'flipped', ['horizontally', 'vertically']) common.propKeyAndValueToClassName(Icon, 'rotated', ['clockwise', 'counterclockwise']) common.propKeyOnlyToClassName(Icon, 'bordered') common.propKeyOnlyToClassName(Icon, 'circular') common.propKeyOnlyToClassName(Icon, 'disabled') common.propKeyOnlyToClassName(Icon, 'fitted') common.propKeyOnlyToClassName(Icon, 'inverted') common.propKeyOnlyToClassName(Icon, 'link') common.propKeyOnlyToClassName(Icon, 'loading') common.propKeyOrValueAndKeyToClassName(Icon, 'corner', [ 'top left', 'top right', 'bottom left', 'bottom right', ]) common.propValueOnlyToClassName(Icon, 'color', SUI.COLORS) common.propValueOnlyToClassName(Icon, 'name', ['money']) common.propValueOnlyToClassName(Icon, 'size', _.without(SUI.SIZES, 'medium')) it('renders as an <i> by default', () => { shallow(<Icon />).should.have.tagName('i') }) describe('aria-hidden', () => { it('should add aria-hidden by default', () => { shallow(<Icon />).should.have.prop('aria-hidden', 'true') }) it('should pass aria-hidden', () => { shallow(<Icon aria-hidden='true' />).should.have.prop('aria-hidden', 'true') shallow(<Icon aria-hidden='false' />).should.have.prop('aria-hidden', 'false') }) it('should passed aria-hidden with aria-label', () => { shallow(<Icon aria-hidden='false' aria-label='icon' />).should.have.prop( 'aria-hidden', 'false', ) }) }) describe('aria-label', () => { it('should not applied by default', () => { shallow(<Icon />).should.have.not.prop('aria-label') }) it('should pass value and omit aria-hidden when is set', () => { const wrapper = shallow(<Icon aria-label='icon' />) wrapper.should.not.have.prop('aria-hidden') wrapper.should.have.prop('aria-label', 'icon') }) }) describe('onClick', () => { it('is called with (e, data) when clicked', () => { const onClick = sandbox.spy() mount(<Icon onClick={onClick} />).simulate('click') onClick.should.have.been.calledOnce() onClick.should.have.been.calledWithMatch({ type: 'click' }, { onClick }) }) it('is not called when "disabled" is true', () => { const onClick = sandbox.spy() const preventDefault = sandbox.spy() mount(<Icon disabled onClick={onClick} />).simulate('click', { preventDefault }) onClick.should.have.not.been.called() preventDefault.should.have.calledOnce() }) }) })
src/Parser/MistweaverMonk/Modules/Items/PetrichorLagniappe.js
mwwscott0/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import { formatNumber } from 'common/format'; import Combatants from 'Parser/Core/Modules/Combatants'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Module from 'Parser/Core/Module'; const debug = false; const PETRICHOR_REDUCTION = 2000; class PetrichorLagniappe extends Module { static dependencies = { combatants: Combatants, abilityTracker: AbilityTracker, }; REVIVAL_BASE_COOLDOWN = 0; totalReductionTime = 0; currentReductionTime = 0; wastedReductionTime = 0; initialWastedReductionTime = 0; casts = 0; lastCastTime = 0; cdReductionUsed = 0; on_initialized() { this.active = this.combatants.selected.hasWrists(ITEMS.PETRICHOR_LAGNIAPPE.id); if (this.active) { this.REVIVAL_BASE_COOLDOWN = 180000 - (this.combatants.selected.traitsBySpellId[SPELLS.TENDRILS_OF_REVIVAL.id] || 0) * 10000; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.REVIVAL.id) { if (this.casts !== 0) { debug && console.log('Time since last Revival cast: ', (event.timestamp - this.lastCastTime), ' //// Revival CD: ', this.REVIVAL_BASE_COOLDOWN); if ((event.timestamp - this.lastCastTime) < this.REVIVAL_BASE_COOLDOWN) { this.cdReductionUsed += 1; } this.wastedReductionTime += (event.timestamp - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime); this.lastCastTime = event.timestamp; this.currentReductionTime = 0; } // Tracking initial Revival cast - Any REM casts before this are considered wasted. if (this.casts === 0) { this.wastedReductionTime += this.currentReductionTime; this.initialWastedReductionTime = this.currentReductionTime; this.casts += 1; this.lastCastTime = event.timestamp; this.currentReductionTime = 0; } } if (spellId === SPELLS.RENEWING_MIST.id) { this.totalReductionTime += PETRICHOR_REDUCTION; this.currentReductionTime += PETRICHOR_REDUCTION; } } on_finished() { if (((this.owner.fight.end_time - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime)) > 0) { this.wastedReductionTime += (this.owner.fight.end_time - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime); } if (debug) { console.log('Time Reduction: ', this.totalReductionTime); console.log('Wasted Reduction:', this.wastedReductionTime); } } item() { const abilityTracker = this.abilityTracker; const getAbility = spellId => abilityTracker.getAbility(spellId); return { item: ITEMS.PETRICHOR_LAGNIAPPE, result: ( <dfn data-tip={`The wasted cooldown reduction from the legendary bracers. ${formatNumber((this.wastedReductionTime / getAbility(SPELLS.REVIVAL.id).casts) / 1000)} seconds (Average wasted cooldown reduction per cast).`}> {formatNumber(this.wastedReductionTime / 1000)} seconds wasted </dfn> ), }; } } export default PetrichorLagniappe;
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/PropsConstructorNoArgs.js
facebook/flow
// @flow import React from 'react'; class MyComponent extends React.Component { constructor() {} defaultProps: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { constructor() {} defaultProps: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
src/backward/Widgets/Subtitle.js
chaitanya0bhagvan/NativeBase
/* @flow */ import React, { Component } from 'react'; import { Text } from 'react-native'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames'; class Subtitle extends Component { render() { return ( <Text ref={c => this._root = c} {...this.props} /> ); } } Subtitle.propTypes = { ...Text.propTypes, style: React.PropTypes.object, }; const StyledSubtitle = connectStyle('NativeBase.Subtitle', {}, mapPropsToStyleNames)(Subtitle); export { StyledSubtitle as Subtitle, };
node_modules/semantic-ui-react/dist/es/views/Feed/FeedLike.js
mowbell/clickdelivery-fed-test
import _extends from 'babel-runtime/helpers/extends'; import _isNil from 'lodash/isNil'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; import Icon from '../../elements/Icon'; /** * A feed can contain a like element. */ function FeedLike(props) { var children = props.children, className = props.className, content = props.content, icon = props.icon; var classes = cx('like', className); var rest = getUnhandledProps(FeedLike, props); var ElementType = getElementType(FeedLike, props); if (!_isNil(children)) { return React.createElement( ElementType, _extends({}, rest, { className: classes }), children ); } return React.createElement( ElementType, _extends({}, rest, { className: classes }), Icon.create(icon), content ); } FeedLike.handledProps = ['as', 'children', 'className', 'content', 'icon']; FeedLike._meta = { name: 'FeedLike', parent: 'Feed', type: META.TYPES.VIEW }; FeedLike.defaultProps = { as: 'a' }; process.env.NODE_ENV !== "production" ? FeedLike.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Shorthand for icon. Mutually exclusive with children. */ icon: customPropTypes.itemShorthand } : void 0; export default FeedLike;
client/routes.js
bbviana/alexandria-mern
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './modules/app/components/App'; import RecipeListPage from './modules/recipe/pages/RecipeListPage' // require.ensure polyfill for node if (typeof require.ensure !== 'function') { require.ensure = function requireModule(deps, callback) { callback(require); }; } /* Workaround for async react routes to work with react-hot-reloader till https://github.com/reactjs/react-router/issues/2182 and https://github.com/gaearon/react-hot-loader/issues/288 is fixed. */ if (process.env.NODE_ENV !== 'production') { // Require async routes only in development for react-hot-reloader to work. // require('./modules/recipe/pages/RecipeCreatePage'); require('./modules/recipe/pages/RecipeListPage'); } // react-router setup with code-splitting // More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/ export default ( <Route path="/" component={App}> <IndexRoute component={RecipeListPage} /> <Route path="/recipes" component={RecipeListPage}/> </Route> );
src/components/RemoveSectionButton.js
BenGoldstein88/redux-chartmaker
import React from 'react'; export default class RemoveSectionButton extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { e.preventDefault() this.props.removeSection(this.props.id); } render() { return ( <div style={{ display: 'inline-block' }}> <button className={'remove-section-button'}onClick={this.handleClick} > <p style={{ position: 'absolute', top: '20%', left: '52%', width: '100%', transform: 'translate(-50%, -50%)' }}>REMOVE SECTION</p> </button> </div> ); } }
packages/cf-component-typography/test/Em.js
manatarms/cf-ui
import React from 'react'; import renderer from 'react-test-renderer'; import Em from '../src/Em'; test('should render', () => { const component = renderer.create(<Em>Em</Em>); expect(component.toJSON()).toMatchSnapshot(); });
src/images/Icons/instagram.js
sourabh-garg/react-starter-kit
import React from 'react'; export default function instagram(props) { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enableBackground="new 0 0 64 64" xmlSpace="preserve" {...props}> <g transform="translate(0, 0)"> <path fill="#444444" d="M32,5.766c8.544,0,9.556,0.033,12.931,0.187c3.642,0.166,7.021,0.895,9.621,3.496 c2.6,2.6,3.329,5.979,3.496,9.621c0.154,3.374,0.187,4.386,0.187,12.931s-0.033,9.556-0.187,12.931 c-0.166,3.642-0.895,7.021-3.496,9.621c-2.6,2.6-5.98,3.329-9.621,3.496c-3.374,0.154-4.386,0.187-12.931,0.187 s-9.557-0.033-12.931-0.187c-3.642-0.166-7.021-0.895-9.621-3.496c-2.6-2.6-3.329-5.979-3.496-9.621 C5.798,41.556,5.766,40.544,5.766,32s0.033-9.556,0.187-12.931c0.166-3.642,0.895-7.021,3.496-9.621 c2.6-2.6,5.979-3.329,9.621-3.496C22.444,5.798,23.456,5.766,32,5.766 M32,0c-8.691,0-9.78,0.037-13.194,0.193 c-5.2,0.237-9.768,1.511-13.436,5.178C1.705,9.037,0.43,13.604,0.193,18.806C0.037,22.22,0,23.309,0,32 c0,8.691,0.037,9.78,0.193,13.194c0.237,5.2,1.511,9.768,5.178,13.436c3.666,3.666,8.234,4.941,13.436,5.178 C22.22,63.963,23.309,64,32,64s9.78-0.037,13.194-0.193c5.199-0.237,9.768-1.511,13.436-5.178c3.666-3.666,4.941-8.234,5.178-13.436 C63.963,41.78,64,40.691,64,32s-0.037-9.78-0.193-13.194c-0.237-5.2-1.511-9.768-5.178-13.436 c-3.666-3.666-8.234-4.941-13.436-5.178C41.78,0.037,40.691,0,32,0L32,0z" /> <path data-color="color-2" fill="#444444" d="M32,15.568c-9.075,0-16.432,7.357-16.432,16.432c0,9.075,7.357,16.432,16.432,16.432 S48.432,41.075,48.432,32C48.432,22.925,41.075,15.568,32,15.568z M32,42.667c-5.891,0-10.667-4.776-10.667-10.667 c0-5.891,4.776-10.667,10.667-10.667c5.891,0,10.667,4.776,10.667,10.667C42.667,37.891,37.891,42.667,32,42.667z" /> <circle data-color="color-2" fill="#444444" cx="49.082" cy="14.918" r="3.84" /> </g> </svg> ); }
src/svg-icons/image/crop-din.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropDin = (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-2zm0 16H5V5h14v14z"/> </SvgIcon> ); ImageCropDin = pure(ImageCropDin); ImageCropDin.displayName = 'ImageCropDin'; ImageCropDin.muiName = 'SvgIcon'; export default ImageCropDin;
HotelAndroid/thanksALot.js
MJ111/hotel-reverse
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, DatePickerAndroid, TouchableWithoutFeedback, Picker, Navigator, } from 'react-native'; const Item = Picker.Item; import Button from 'react-native-button'; /*---------------------------------------------------------------- Structure Header: Your Wish List Body: Bidding Info Footer: <Are you sure?> <No, I'm not sure!> buttons ----------------------------------------------------------------*/ class ThanksALot extends Component { constructor(props) { super(props); console.log('thnaxk'); } _handlePress(where) { this.props.navigator.push({id: where}); // console.log('nav: ', this.props.navigator); } render() { return ( <View style={{flex: 1}}> <Text style={styles.appName}> 이용해 주셔서 감사합니다!!! </Text> <View style={styles.rowContainer}> <Button style={styles.searchBtnText} containerStyle={styles.searchBtn} onPress={() => this._handlePress('search')}> HOME </Button> </View> </View> ); } } const styles = StyleSheet.create({ rowContainer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', margin: 10, }, smallRowContainer: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-start', marginLeft: 30, marginTop: 2, marginBottom: 2 }, appName: { fontSize: 20, textAlign: 'center', color: '#000', margin: 10, }, label: { width: 60, textAlign: 'left', margin: 10, color: 'black', }, searchBtn: { width: 150, padding:10, height: 30, overflow: 'hidden', borderColor: 'black', borderWidth: 2, borderStyle: 'solid', backgroundColor: 'green', justifyContent: 'center', alignItems: 'center', }, searchBtnText: { fontSize: 15, color: 'white', }, list: { flex: 1, padding: 30, backgroundColor: 'rgb(39, 174, 96)' }, row: { margin: 8, flexDirection: 'row', justifyContent: 'space-between' }, title: { fontSize: 20, color: 'white' } }); export default ThanksALot;
src/pages/404.js
derrickyoo/derrickyoo.com
import React from 'react' import Layout from '../components/layout' import SEO from '../components/seo' const NotFoundPage = () => ( <Layout> <SEO title="404: Not found" /> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) export default NotFoundPage
src/js/index.js
Tonius/factolculator
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.css'; import App from './App'; // Render the main app component, starting the web application. ReactDOM.render(<App />, document.getElementById('app'));
docs/src/app/components/pages/components/SvgIcon/ExampleIcons.js
skarnecki/material-ui
import React from 'react'; import ActionHome from 'material-ui/svg-icons/action/home'; import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff'; import FileCloudDownload from 'material-ui/svg-icons/file/cloud-download'; import HardwareVideogameAsset from 'material-ui/svg-icons/hardware/videogame-asset'; import {red500, yellow500, blue500} from 'material-ui/styles/colors'; const iconStyles = { marginRight: 24, }; const SvgIconExampleIcons = () => ( <div> <ActionHome style={iconStyles} /> <ActionFlightTakeoff style={iconStyles} color={red500} /> <FileCloudDownload style={iconStyles} color={yellow500} /> <HardwareVideogameAsset style={iconStyles} color={blue500} /> </div> ); export default SvgIconExampleIcons;
react/gameday2/components/embeds/EmbedNotSupported.js
fangeugene/the-blue-alliance
import React from 'react' const EmbedNotSupported = () => { const containerStyles = { margin: 20, textAlign: 'center', } const textStyles = { color: '#ffffff', } return ( <div style={containerStyles}> <p style={textStyles}>This webcast is not supported.</p> </div> ) } export default EmbedNotSupported
src/index.js
karim88/karim88.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.hydrate(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
src/components/Preview/Preview.js
chengjianhua/templated-operating-system
import React, { Component } from 'react'; import ReactServer from 'react-dom/server'; import ReactDOM, { findDOMNode } from 'react-dom'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; // import s from './Preview.css'; const styles = { root: { width: '375px', height: '667px', }, }; // @withStyles(s) export default class MyComponent extends Component { static propTypes = { children: PropTypes.node, }; static defaultProps = { children: null, }; componentDidMount() { // const { contentWindow: { document: iframeDocument } } = this.iframe; // console.log(iframeDocument); } iframeRef = (ref) => { this.iframe = ref; }; renderContent = () => { const { children } = this.props; const html = ReactDOM.renderToString( <html lang="zh-CN"> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>预览手机展示</title> <body> {children} </body> </html>, ); return html; }; render() { const { children, ...props } = this.props; return ( <div ref={this.iframeRef} style={styles.root} {...props} > {children} </div> ); } }
src/components/Form/InlineInput/__tests__/InlineInput.js
thegrinder/basic-styled-uikit
import React from 'react'; import { ThemeProvider } from 'styled-components'; import { render, cleanup } from '@testing-library/react'; import theme from '../../../../theme/theme'; import InlineInput from '../InlineInput'; const renderComponent = (props = {}) => render( <ThemeProvider theme={theme}> <InlineInput {...props} /> </ThemeProvider> ); describe('<InlineInput />', () => { afterEach(cleanup); it('should render correctly with default props', () => { const { container: { firstChild }, } = renderComponent(); expect(firstChild).toBeDefined(); expect(firstChild).toMatchSnapshot(); }); it('should render correctly with custom props', () => { const spinner = <span data-testid="spinner" />; const { container: { firstChild }, getByTestId, } = renderComponent({ invalid: false, submitting: true, renderSpinner: spinner, }); const spinnerElement = getByTestId('spinner'); expect(firstChild).toBeDefined(); expect(firstChild).toContainElement(spinnerElement); }); });
client/src/components/Admin/Categories/CategoryList.js
hutchgrant/react-boilerplate
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../../actions/admin'; class CategoryList extends Component { render() { return ( <div> <h2 className="text-center">Category List</h2> </div> ); } }; function mapStateToProps({ auth }) { return { auth }; } export default connect(mapStateToProps, actions)(CategoryList);
frontend/src/admin/header/LogoutButton.js
rabblerouser/core
import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { logout } from '../actions/'; import { Button } from '../common'; const StyledLogoutButton = styled(Button)` background-color: ${props => props.theme.primaryColour}; color: white; border: 1px solid white; border-radius: 4px; font-size: 20px; `; const LogoutButton = ({ onLogout }) => ( <StyledLogoutButton onClick={onLogout}>Logout</StyledLogoutButton> ); const mapDispatchToProps = dispatch => ({ onLogout: () => dispatch(logout()), }); export default connect(() => ({}), mapDispatchToProps)(LogoutButton);
ui/js/components/Show.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { loadItem, unloadItem } from '../actions'; import ItemHeader from './ItemHeader'; import Loading from './Loading'; import NotFound from './NotFound'; class Show extends Component { componentDidMount() { this._load(this.props); } componentWillReceiveProps(nextProps) { if ((nextProps.category !== this.props.category || nextProps.id !== this.props.id || !nextProps.item)) { this._load(nextProps); } if (nextProps.item) { document.title = nextProps.item.name; } } componentWillUnmount() { const { category, dispatch, id } = this.props; dispatch(unloadItem(category, id)); } _load(props) { const { category, dispatch, id, item, } = props; if (item) { document.title = item.name; } else { dispatch(loadItem(category, id)); } } render() { const { actions, category, Contents, item, notFound, title, } = this.props; let contents; if (item) { contents = <Contents item={item} />; } else if (notFound) { contents = <NotFound />; } else { contents = <Loading />; } return ( <main> <ItemHeader title={title} category={category} item={item} actions={actions} /> {contents} </main> ); } } Show.propTypes = { actions: PropTypes.arrayOf(PropTypes.element), category: PropTypes.string.isRequired, Contents: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, id: PropTypes.string.isRequired, item: PropTypes.object, notFound: PropTypes.bool, title: PropTypes.string, }; Show.defaultProps = { actions: [], item: undefined, notFound: false, title: undefined, }; Show.contextTypes = { router: PropTypes.any, }; const select = (state, props) => ({ id: props.match.params.id, item: state[props.match.params.id], notFound: state.notFound[props.match.params.id], }); export default connect(select)(Show);
src/js/components/icons/base/LinkBottom.js
odedre/grommet-final
/** * @description LinkBottom SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M12,5 L12,23 M4,13 L12,5 L20,13 M2,2 L22,2" transform="matrix(1 0 0 -1 0 24)"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-link-bottom`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'link-bottom'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,5 L12,23 M4,13 L12,5 L20,13 M2,2 L22,2" transform="matrix(1 0 0 -1 0 24)"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'LinkBottom'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
docs/src/examples/elements/Divider/Types/DividerExampleHorizontal.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Divider, Input, Segment } from 'semantic-ui-react' const DividerExampleHorizontal = () => ( <Segment basic textAlign='center'> <Input action={{ color: 'blue', content: 'Search' }} icon='search' iconPosition='left' placeholder='Order #' /> <Divider horizontal>Or</Divider> <Button color='teal' content='Create New Order' icon='add' labelPosition='left' /> </Segment> ) export default DividerExampleHorizontal
src/components/BannerNavigation/BannerNavigationWithContent.js
wfp/ui
import PropTypes from 'prop-types'; import React from 'react'; import { BannerNavigation, BannerNavigationItem } from './BannerNavigation'; import Search from '../Search'; import Link from '../Link'; const linkList = [ { name: 'WFPgo', link: 'https://go.wfp.org/' }, { name: 'Communities', link: 'https://communities.wfp.org/' }, { name: 'Manuals', link: 'https://manuals.wfp.org/' }, { name: 'GoDocs', link: 'https://godocs.wfp.org/' }, { name: 'WeLearn', link: 'https://welearn.wfp.org/' }, { name: 'Dashboard', link: 'https://dashboard.wfp.org/' }, { name: 'OPweb', link: 'https://opweb.wfp.org/' }, { name: 'Self-Service', link: 'https://selfservice.go.wfp.org/' }, { name: 'UN Booking Hub', link: 'https://humanitarianbooking.wfp.org/' }, { name: 'WFP.org', link: 'https://wfp.org/' }, ]; const BannerNavigationWithContent = ({ searchOnChange, search, ...other }) => ( <BannerNavigation {...other}> {linkList.map((e) => ( <BannerNavigationItem> <Link href={e.link} target="_blank"> {e.name} </Link> </BannerNavigationItem> ))} </BannerNavigation> ); BannerNavigationWithContent.propTypes = { /** * The CSS class name to be placed on the wrapping element. */ className: PropTypes.string, /** * Specify the max-width on desktop devices (same as \`Wrapper\` component) */ pageWidth: PropTypes.oneOf(['sm', 'md', 'lg', 'full']), /** * Allows to disable the search input */ search: PropTypes.bool, /** * A onChange Function for the search */ searchOnChange: PropTypes.func, }; BannerNavigationWithContent.defaultProps = { search: false, searchOnChange: () => {}, }; export { BannerNavigationWithContent };
modules/Redirect.js
aaron-goshine/react-router
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { formatPattern } from './PatternUtils' import { falsy } from './InternalPropTypes' const { string, object } = React.PropTypes /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ const Redirect = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.from) route.path = route.from route.onEnter = function (nextState, replace) { const { location, params } = nextState let pathname if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params) } else if (!route.to) { pathname = location.pathname } else { let routeIndex = nextState.routes.indexOf(route) let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1) let pattern = parentPattern.replace(/\/*$/, '/') + route.to pathname = formatPattern(pattern, params) } replace({ pathname, query: route.query || location.query, state: route.state || location.state }) } return route }, getRoutePattern(routes, routeIndex) { let parentPattern = '' for (let i = routeIndex; i >= 0; i--) { const route = routes[i] const pattern = route.path || '' parentPattern = pattern.replace(/\/*$/, '/') + parentPattern if (pattern.indexOf('/') === 0) break } return '/' + parentPattern } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Redirect> elements are for router configuration only and should not be rendered' ) } }) export default Redirect
src/encoded/static/components/item-pages/components/WorkflowDetailPane/ParameterDetailBody.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; export const ParameterDetailBody = React.memo(function ParameterDetailBody({ node, minHeight }){ return ( <div style={typeof minHeight === 'number' ? { minHeight } : null}> <div className="information"> <div className="row"> <div className="col col-sm-4 box"> <span className="text-600">Parameter Name</span> <h3 className="text-300 text-truncate">{ node.name || node.meta.name }</h3> </div> <div className="col-sm-8 box"> <span className="text-600">Value Used</span> <h4 className="text-300 text-truncate"> <code>{ node.meta.run_data.value }</code> </h4> </div> </div> </div> <hr/> </div> ); });
src/containers/Mcml/Mcml.js
hahoocn/hahoo-admin
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar'; import FormControl from 'react-bootstrap/lib/FormControl'; import toFloat from 'validator/lib/toFloat'; import isDecimal from 'validator/lib/isDecimal'; import config from './config'; import { filterPage } from '../../utils/filter'; import ListRow from './ListRow'; import { Navbar, PageWrapper, PageHeader, List, BtnAdd, BtnRefresh, Pagination, Dialog, Toast, ShowError } from '../../components'; import { getList, setListStatus, publish, del, order, getScrollPosition, cleanError, cleanLoading } from '../../actions/mcml'; class Mcml extends React.Component { static propTypes = { data: React.PropTypes.object, dispatch: React.PropTypes.func, params: React.PropTypes.object } static contextTypes = { router: React.PropTypes.object.isRequired } constructor(props) { super(props); this.state.pageSize = config.pageSize; this.pageSelect = this.pageSelect.bind(this); this.handleDelConfirm = this.handleDelConfirm.bind(this); this.changeOrderIdConfirm = this.changeOrderIdConfirm.bind(this); this.refresh = this.refresh.bind(this); } state = { pageSize: 10, isLoading: false, del: { isShowDialog: false, id: undefined, }, order: { isShowDialog: false, id: undefined, orderId: undefined, newOrderId: undefined, } } componentWillMount() { this.setState({ isLoading: true }); const { data, dispatch } = this.props; if (data.error) { dispatch(cleanError()); } if (data.isLoading || data.isUpdating) { dispatch(cleanLoading()); } } componentDidMount() { const page = filterPage(this.props.params.page); if (page === -1) { this.context.router.replace('/notfound'); } else { const { data, dispatch } = this.props; if (page !== data.page || data.items.length === 0 || (data.listUpdateTime && ((Date.now() - data.listUpdateTime) > config.listRefreshTime))) { dispatch(setListStatus('initPage')); dispatch(getList(config.api.resource, page, this.state.pageSize)); } } if (this.state.isLoading) { setTimeout(() => { this.setState({ isLoading: false }); }, 50); } } shouldComponentUpdate(nextProps, nextState) { const { data } = this.props; const page = filterPage(nextProps.params.page); if (page === -1) { return false; } if (page !== data.page || data.items.length === 0 || (data.listUpdateTime && ((Date.now() - data.listUpdateTime) > config.listRefreshTime))) { return true; } if (data.shouldUpdate || nextProps.data.shouldUpdate) { return true; } if (nextState.del !== this.state.del || nextState.order !== this.state.order || nextState.isLoading !== this.state.isLoading) { return true; } return false; } componentDidUpdate(prevProps, prevState) { const { data, dispatch } = this.props; if (!data.isLoading && prevProps.data.isLoading && !data.error) { switch (data.listStatus) { case 'initPage': window.scrollTo(0, this.props.data.scrollY); break; case 'switchingPage': window.scrollTo(0, 0); this.context.router.push(`/${config.module}/list/${data.page}`); break; default: } dispatch(setListStatus('ok')); } else { // 直接从浏览器输入页码 const page = filterPage(this.props.params.page); if (page === -1) { this.context.router.replace('/notfound'); } else if (!data.isLoading && page !== data.page && !data.error && data.listStatus === 'ok') { dispatch(getList(config.api.resource, page, this.state.pageSize)); } if (prevState.isLoading && !this.state.isLoading) { window.scrollTo(0, this.props.data.scrollY); } } } componentWillUnmount() { this.props.dispatch(getScrollPosition(window.scrollY)); } pageSelect(page) { const { dispatch } = this.props; dispatch(setListStatus('switchingPage')); dispatch(getList(config.api.resource, page, this.state.pageSize)); } refresh() { const { dispatch, data } = this.props; dispatch(getList(config.api.resource, data.page, this.state.pageSize)); } handleDelConfirm(code) { if (code === 1) { this.props.dispatch(del(config.api.resource, this.state.del.id)); } this.setState({ del: { isShowDialog: false, id: undefined } }); } changeOrderIdConfirm(code) { if (code === 1) { if (isDecimal(`${this.state.order.newOrderId}`)) { const newOrderId = toFloat(`${this.state.order.newOrderId}`); if (newOrderId && newOrderId > 0 && newOrderId !== toFloat(`${this.state.order.orderId}`)) { const { dispatch, params } = this.props; dispatch(order(config.api.resource, this.state.order.id, 'changeOrderId', params.page, this.state.pageSize, newOrderId)); } } } this.setState({ order: { isShowDialog: false, id: undefined, orderId: undefined, newOrderId: undefined } }); } render() { const { data, dispatch, params } = this.props; const { page } = params; const { pageSize } = this.state; let loading; if (data.isLoading || this.state.isLoading) { loading = <Toast type="loading" title="加载数据" isBlock />; } if (data.isUpdating) { loading = <Toast type="loading" title="正在更新" isBlock />; } let error; if (!loading && data.error) { error = <ShowError error={data.error} key={Math.random()} onClose={() => dispatch(cleanError())} />; } let pageWrapper; let dialog; if (!this.state.isLoading && data.items && data.items.length > 0) { if (this.state.del.isShowDialog) { dialog = <Dialog title="确认" info="您确定删除吗?" type="confirm" onClick={this.handleDelConfirm} />; } if (this.state.order.isShowDialog) { dialog = (<Dialog title="修改排序码" info={<FormControl type="number" value={this.state.order.newOrderId} onChange={e => this.setState({ order: Object.assign({}, this.state.order, { newOrderId: e.target.value }) })} />} type="confirm" onClick={this.changeOrderIdConfirm} />); } const rows = data.items.map(item => (<ListRow module={config.module} key={item.id} item={item} onDelete={id => this.setState({ del: { isShowDialog: true, id } })} onPublish={id => dispatch(publish(config.api.resource, id, true))} onUnPublish={id => dispatch(publish(config.api.resource, id, false))} onMoveUp={id => dispatch(order(config.api.resource, id, 'up', page, pageSize))} onMoveDown={id => dispatch(order(config.api.resource, id, 'down', page, pageSize))} onMoveTo={(id, orderId) => dispatch(order(config.api.resource, id, 'changeOrderId', page, pageSize, orderId))} onPopOrderIdPannel={(id, orderId) => this.setState({ order: { isShowDialog: true, id, orderId, newOrderId: orderId } })} />)); const pagination = (<Pagination page={data.page} pageSize={pageSize} recordCount={data.totalCount} pageSelect={this.pageSelect} />); pageWrapper = (<div> <PageHeader title={config.moduleName} subTitle="列表"> <ButtonToolbar> <BtnAdd onItemClick={() => this.context.router.push(`/${config.module}/add`)} /> <BtnRefresh onItemClick={this.refresh} /> </ButtonToolbar> </PageHeader> <List> {rows && rows} </List> {pagination && pagination} </div>); } return ( <div> <Helmet title={config.pageTitle} /> <Navbar activeKey={config.module} /> {dialog && dialog} {error && error} {loading && loading} <PageWrapper> {pageWrapper} </PageWrapper> </div> ); } } const mapStateToProps = (state) => { const select = { data: state.mcml }; return select; }; export default connect(mapStateToProps)(Mcml);
frontend/src/Settings/Indexers/Indexers/AddIndexerModal.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import AddIndexerModalContentConnector from './AddIndexerModalContentConnector'; function AddIndexerModal({ isOpen, onModalClose, ...otherProps }) { return ( <Modal isOpen={isOpen} onModalClose={onModalClose} > <AddIndexerModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } AddIndexerModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default AddIndexerModal;
src/js/components/Map.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import CSSClassnames from '../utils/CSSClassnames'; import Intl from '../utils/Intl'; const CLASS_ROOT = CSSClassnames.MAP; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class ResourceMap extends Component { constructor(props, context) { super(props, context); this._onResize = this._onResize.bind(this); this._layout = this._layout.bind(this); this._onEnter = this._onEnter.bind(this); this._onLeave = this._onLeave.bind(this); this.state = { ...(this._stateFromProps(props)), height: 100, width: 100, paths: [] }; } componentDidMount () { window.addEventListener('resize', this._onResize); this._layout(); } componentWillReceiveProps (nextProps) { this.setState(this._stateFromProps(nextProps), this._layout); } componentWillUnmount () { window.removeEventListener('resize', this._onResize); } _hashItems (data) { let result = {}; data.categories.forEach(category => { category.items.forEach(item => { result[item.id] = item; }); }); return result; } _children (parentId, links, items) { let result = []; links.forEach(link => { if (link.parentId === parentId) { result.push(items[link.childId]); } }); return result; } _parents (childId, links, items) { let result = []; links.forEach((link) => { if (link.childId === childId) { result.push(items[link.parentId]); } }); return result; } _buildAriaLabels (data, items) { const { intl } = this.context; let labels = {}; data.categories.forEach(category => { category.items.forEach(item => { const children = this._children(item.id, data.links, items); const parents = this._parents(item.id, data.links, items); let message = ''; if (children.length === 0 && parents.length === 0) { message = Intl.getMessage(intl, 'No Relationship'); } else { if (parents.length > 0) { const prefix = Intl.getMessage(intl, 'Parents'); const labels = parents.map(item => item.label || item.node).join(); message += `${prefix}: (${labels})`; } if (children.length > 0) { if (parents.length > 0) { message += ', '; } const prefix = Intl.getMessage(intl, 'Children'); const labels = children.map(item => item.label || item.node).join(); message += `${prefix}: (${labels})`; } } labels[item.id] = message; }); }); return labels; } _stateFromProps (props, state = {}) { const activeId = props.hasOwnProperty('active') ? props.active : state.activeId; const items = this._hashItems(props.data); return { activeId: activeId, ariaLabels: this._buildAriaLabels(props.data, items), items: items }; } _coords (id, containerRect) { const element = document.getElementById(id); const rect = element.getBoundingClientRect(); const left = rect.left - containerRect.left; const top = rect.top - containerRect.top; const midX = left + (rect.width / 2); const midY = top + (rect.height / 2); return { top: [midX, top], bottom: [midX, top + rect.height], left: [left, midY], right: [left + rect.width, midY] }; } _buildPaths (map) { const { linkColorIndex, data: { links }, vertical } = this.props; const { activeId } = this.state; const rect = map.getBoundingClientRect(); const paths = links.map((link, index) => { const parentCoords = this._coords(link.parentId, rect); const childCoords = this._coords(link.childId, rect); let p1, p2; if (vertical) { if (parentCoords.right[0] < childCoords.left[0]) { p1 = parentCoords.right; p2 = childCoords.left; } else { p1 = parentCoords.left; p2 = childCoords.right; } } else { if (parentCoords.bottom[1] < childCoords.top[1]) { p1 = parentCoords.bottom; p2 = childCoords.top; } else { p1 = parentCoords.top; p2 = childCoords.bottom; } } let commands = `M${p1[0]},${p1[1]}`; const midX = p1[0] + ((p2[0] - p1[0]) / 2); const midY = p1[1] + ((p2[1] - p1[1]) / 2); if (vertical) { commands += ` Q ${midX + ((p1[0] - midX) / 2)},${p1[1]}` + ` ${midX},${midY}`; commands += ` Q ${midX - ((p1[0] - midX) / 2)},${p2[1]}` + ` ${p2[0]},${p2[1]}`; } else { commands += ` Q ${p1[0]},${midY + ((p1[1] - midY) / 2)}` + ` ${midX},${midY}`; commands += ` Q ${p2[0]},${midY - ((p1[1] - midY) / 2)}` + ` ${p2[0]},${p2[1]}`; } const pathColorIndex = link.colorIndex || linkColorIndex; const classes = classnames( `${CLASS_ROOT}__path`, { [`${CLASS_ROOT}__path--active`]: (activeId === link.parentId || activeId === link.childId), [`${COLOR_INDEX}-${pathColorIndex}`]: pathColorIndex } ); return ( <path key={index} fill="none" className={classes} d={commands} /> ); }); return paths; } _layout () { const map = findDOMNode(this._mapRef); if (map) { this.setState({ width: map.scrollWidth, height: map.scrollHeight, paths: this._buildPaths(map) }); } } _onResize () { // debounce clearTimeout(this._layoutTimer); this._layoutTimer = setTimeout(this._layout, 50); } _onEnter (id) { this.setState({activeId: id}, this._layout); if (this.props.onActive) { this.props.onActive(id); } } _onLeave () { this.setState({activeId: undefined}, this._layout); if (this.props.onActive) { this.props.onActive(undefined); } } _renderItems (items) { const { data } = this.props; const { activeId, ariaLabels } = this.state; return items.map((item, index) => { const active = activeId === item.id || data.links.some(link => { return ((link.parentId === item.id || link.childId === item.id) && (link.parentId === activeId || link.childId === activeId)); }); const classes = classnames( `${CLASS_ROOT}__item`, { [`${CLASS_ROOT}__item--active`]: active, [`${CLASS_ROOT}__item--plain`]: (item.node && typeof item.node !== 'string') } ); return ( <li key={index} id={item.id} className={classes} aria-label={`${item.label || item.node}, ${ariaLabels[item.id]}`} onMouseEnter={this._onEnter.bind(this, item.id)} onMouseLeave={this._onLeave.bind(this, item.id)}> {item.node || item.label} </li> ); }); } _renderCategories (categories) { return categories.map(category => { return ( <li key={category.id} className={`${CLASS_ROOT}__category`}> <div className={`${CLASS_ROOT}__category-label`}> {category.label} </div> <ul className={`${CLASS_ROOT}__category-items`}> {this._renderItems(category.items)} </ul> </li> ); }); } render () { const { className, data, vertical, ...props } = this.props; delete props.active; delete props.colorIndex; delete props.linkColorIndex; delete props.onActive; const { height, paths, width } = this.state; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--vertical`]: vertical }, className ); let categories; if (data.categories) { categories = this._renderCategories(data.categories); } return ( <div ref={ref => this._mapRef = ref} {...props} className={classes}> <svg className={`${CLASS_ROOT}__links`} width={width} height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="xMidYMid meet"> {paths} </svg> <ol className={`${CLASS_ROOT}__categories`}> {categories} </ol> </div> ); } } ResourceMap.contextTypes = { intl: PropTypes.object }; ResourceMap.propTypes = { active: PropTypes.string, data: PropTypes.shape({ categories: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.node, items: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.string, node: PropTypes.node })) })), links: PropTypes.arrayOf(PropTypes.shape({ childId: PropTypes.string.isRequired, colorIndex: PropTypes.string, parentId: PropTypes.string.isRequired })) }).isRequired, linkColorIndex: PropTypes.string, onActive: PropTypes.func, vertical: PropTypes.bool }; ResourceMap.defaultProps = { linkColorIndex: 'graph-1' };
src/services/TplEmbeddedLoader.js
webcerebrium/ec-react15-lib
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Logger } from './Logger'; import { getDocumentContext } from './TplContext'; import { matchConditions } from './DocumentCondition'; import { findDocumentElements } from './DocumentSelector'; import { downloadTemplateData } from './TplRouteData'; import ApplicationContainer from './../containers/ApplicationContainer'; const getTemplateDocument = tpl => (tpl ? `--Template-${tpl}` : ''); export const onStartApplications = (store, mount, callback) => { const context = getDocumentContext(store.getState()); mount.forEach((potentialMount) => { // 1) - there has to be potentialMount.selector on the page currently const elementRoot = findDocumentElements(potentialMount.selector, document); // eslint-disable-line Logger.of('TplEmbeddedLoader.onStartApplication').info('check for mounting', potentialMount, 'elementRoot=', elementRoot); if (elementRoot) { // 2) - potentialMount.condition should be valid. let match = true; if (potentialMount.condition) { match = matchConditions({}, potentialMount.condition, context); Logger.of('TplEmbeddedLoader.onStartApplication').info('check for conditions', potentialMount.condition, match); } if (match) { // confirmed 'route' match const route = potentialMount; const { dispatch } = store; // we have both element and condition match, mounting it // and how to pass ... anything... ? it has global redux mapping... Logger.of('TplEmbeddedLoader.onStartApplication').info('mounting template', potentialMount.template); const tpl = getTemplateDocument(potentialMount.template); dispatch({ type: 'SET_DATA', payload: ['template', tpl] }); downloadTemplateData({ route, tpl, store, callback: () => { // notifying all reducers of what we currently have in the store. // this is used for setting up defaults at them. dispatch({ type: 'INIT_DATA', payload: store.getState() }); // Logger.of('TplRouteLoader.Ready').info('state=', store.getState()); // onDataReady(route, getDocumentContext(store.getState(), dispatch), callback); // route is released, we are starting to run hooks from plugins const ecOptions = store.getState().globals.ecOptions; if (ecOptions.plugins && ecOptions.plugins.length) { ecOptions.plugins.forEach((plugin) => { if (typeof plugin.onDataReady === 'function') { plugin.onDataReady({ route, tpl, store }); } }); } if (typeof callback === 'function') callback(); } }); const application = ( <Provider store={store}> <ApplicationContainer /> </Provider> ); render(application, elementRoot); } } }); }; export default { onStartApplications };
react/features/mobile/navigation/components/conference/ConferenceNavigationContainerRef.js
jitsi/jitsi-meet
import React from 'react'; export const conferenceNavigationRef = React.createRef(); /** * User defined navigation action included inside the reference to the container. * * @param {string} name - Destination name of the route that has been defined somewhere. * @param {Object} params - Params to pass to the destination route. * @returns {Function} */ export function navigate(name: string, params?: Object) { return conferenceNavigationRef.current?.navigate(name, params); } /** * User defined navigation action included inside the reference to the container. * * @returns {Function} */ export function goBack() { return conferenceNavigationRef.current?.goBack(); } /** * User defined navigation action included inside the reference to the container. * * @param {Object} params - Params to pass to the destination route. * @returns {Function} */ export function setParams(params: Object) { return conferenceNavigationRef.current?.setParams(params); }
Redux/src/index.js
il-tmfv/ReactTutorialMaxP
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' require('./styles/app.css') import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <div className='app'> <App /> </div> </Provider>, document.getElementById('root') )
client/providers/ServerProvider.js
Sing-Li/Rocket.Chat
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { Info as info } from '../../app/utils'; import { ServerContext } from '../contexts/ServerContext'; import { APIClient } from '../../app/utils/client'; const absoluteUrl = (path) => Meteor.absoluteUrl(path); const callMethod = (methodName, ...args) => new Promise((resolve, reject) => { Meteor.call(methodName, ...args, (error, result) => { if (error) { reject(error); return; } resolve(result); }); }); const callEndpoint = (httpMethod, endpoint, ...args) => { const allowedHttpMethods = ['get', 'post', 'delete']; if (!httpMethod || !allowedHttpMethods.includes(httpMethod.toLowerCase())) { throw new Error('Invalid http method provided to "useEndpoint"'); } if (!endpoint) { throw new Error('Invalid endpoint provided to "useEndpoint"'); } if (endpoint[0] === '/') { return APIClient[httpMethod.toLowerCase()](endpoint.slice(1), ...args); } return APIClient.v1[httpMethod.toLowerCase()](endpoint, ...args); }; const uploadToEndpoint = (endpoint, params, formData) => { if (endpoint[0] === '/') { return APIClient.upload(endpoint.slice(1), params, formData).promise; } return APIClient.v1.upload(endpoint, params, formData).promise; }; const getStream = (streamName, options = {}) => new Meteor.Streamer(streamName, options); const contextValue = { info, absoluteUrl, callMethod, callEndpoint, uploadToEndpoint, getStream, }; export function ServerProvider({ children }) { return <ServerContext.Provider children={children} value={contextValue} />; }
app/javascript/mastodon/features/ui/components/column_header.js
mhffdq/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <i className={`fa fa-fw fa-${icon} column-header__icon`} />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/Post.js
drop-table-ryhmatyo/tekislauta-front
import React, { Component } from 'react'; import { Link } from 'react-router'; import Utilities from './Utilities'; import './styles/Post.css'; class Post extends Component { constructor(props) { super(props); this.containerClassName = 'Post Post--reply'; } getIdColor() { const ip = this.props.data.ip; let r = parseInt(ip.substr(0, 2), 16); let g = parseInt(ip.substr(2, 2), 16); let b = parseInt(ip.substr(4, 2), 16); const modifier = parseInt(ip.substr(6, 2), 16); // the ip has 4 bytes, we only need 3. We could use the last one for alpha but that's trash // instead, we'll just xor r ^= modifier; g ^= modifier; b ^= modifier; let hsl = Utilities.RgbToHsl(r, g, b); hsl['s'] -= 20; // desaturate a little for that web 3.0 look return `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`; } render() { const idStyle = { backgroundColor: this.getIdColor() } return ( <div className={this.containerClassName} id={'p' + this.props.data.id}> <div className='Post__header'> <span className='Post__header__title'> <Link className='Post__header__title__anchor' to={'/boards/' + this.props.board + '/thread/' + this.props.data.id}> {this.props.data.subject} </Link> </span> <span id={this.props.data.id} className='Post__header__posterName'> Anonymous </span> <span className='Post__header__id'>(ID: <span className='Post__header__id__value' style={idStyle}>{this.props.data.ip}</span>) </span> <time className='Post__header__timestamp'>{new Date(this.props.data.post_time * 1000).toLocaleString("fi-FI") }</time> <span className='Post__header__postNumber'> No.{this.props.data.id}</span> <ReplyLink onClickFunc={this.props.onReplyClicked} board={this.props.board} postId={this.props.data.id} /> </div> <div className='Post__content'> <ThreadReply message={this.props.data.message} /> </div> </div> ); } } class ReplyLink extends Component { render() { const link = `/boards/${this.props.board}/thread/${this.props.postId}`; if (this.props.onClickFunc !== undefined) { return ( <span className='ReplyLink'> [<a href='#' onClick={() => this.props.onClickFunc(this.props.postId) }>Reply</a>] </span> ); } else { return ( <span className='ReplyLink'> [<Link to={link}>Reply</Link>] </span> ); } } } class ThreadReply extends Component { render() { var replyId = this.props.message.match(/>> \b\d{1,8}/); if (replyId) { replyId = replyId[0]; return ( <p> <a href={'#' + replyId.substr(3) }>{replyId}</a> {this.props.message.replace(/>> \b\d{1,8}/, '') } </p> ) } return ( <p>{this.props.message}</p> ); } } class OriginalPost extends Post { // thread starter constructor(props) { super(props); this.containerClassName = 'Post Post--op'; } } class ThreadlistOriginalPost extends OriginalPost { constructor(props) { super(props); this.containerClassName = 'Post Post--op Post--op_threadlist'; } } export { Post as default, OriginalPost, ThreadlistOriginalPost };
docs/app/Examples/modules/Dropdown/Types/DropdownExamplePointingTwo.js
koenvg/Semantic-UI-React
import React from 'react' import { Dropdown, Menu } from 'semantic-ui-react' const DropdownExamplePointingTwo = () => ( <Menu vertical> <Menu.Item> Home </Menu.Item> <Dropdown text='Messages' pointing='left' className='link item'> <Dropdown.Menu> <Dropdown.Item>Inbox</Dropdown.Item> <Dropdown.Item>Starred</Dropdown.Item> <Dropdown.Item>Sent Mail</Dropdown.Item> <Dropdown.Item>Drafts (143)</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item>Spam (1009)</Dropdown.Item> <Dropdown.Item>Trash</Dropdown.Item> </Dropdown.Menu> </Dropdown> <Menu.Item> Browse </Menu.Item> <Menu.Item> Help </Menu.Item> </Menu> ) export default DropdownExamplePointingTwo
packages/screenie-cli/src/browser-reporter/components/tests-chart.js
ParmenionUX/screenie
import React from 'react' import { connect } from 'react-redux' export default connect( state => ({ status: state.status, }), )(({ status }) => <div style={styles.container}> <svg style={styles.svg}> {renderTests(status.tests)} </svg> </div> ) const PADDING = 20 const TEST_PADDING = 30 const SNAPSHOT_PADDING = 5 const SNAPSHOT_SIZE = 16 function renderTests(tests) { let x = PADDING return tests.map(test => { const startX = x if (test.snapshots != null) { const snapshots = test.snapshots.map(snapshot => { const thisX = x x += SNAPSHOT_SIZE + SNAPSHOT_PADDING return renderSnapshotOrTest(snapshot, test, thisX) }) return [ <rect x={startX} width={x - startX} y={0} height={SNAPSHOT_SIZE + PADDING + PADDING} fill="whitesmoke" />, ...snapshots, <line x1={x + SNAPSHOT_SIZE + (TEST_PADDING / 2)} x2={x + SNAPSHOT_SIZE + (TEST_PADDING / 2)} y1={PADDING} y2={PADDING + SNAPSHOT_SIZE} stroke="gray" strokeWidth={1} />, ] } const thisX = x x += SNAPSHOT_SIZE + TEST_PADDING return [ renderSnapshotOrTest(test, null, thisX), <line x1={thisX + SNAPSHOT_SIZE + (TEST_PADDING / 2)} x2={thisX + SNAPSHOT_SIZE + (TEST_PADDING / 2)} y1={PADDING} y2={PADDING + SNAPSHOT_SIZE} stroke="gray" strokeWidth={1} />, ] }) } function renderSnapshotOrTest(testOrSnapshot, parentTest, x) { let snapshotStatusStyle = null if (testOrSnapshot.passed) { snapshotStatusStyle = styles.snapshotPassed } else if (testOrSnapshot.passed === false) { snapshotStatusStyle = styles.snapshotFailed } return ( <rect style={{ ...styles.snapshot, ...snapshotStatusStyle, }} x={x} y={PADDING} > <title> {parentTest != null ? `${parentTest.name} - ${testOrSnapshot.name}` : testOrSnapshot.name } </title> </rect> ) } const styles = { container: { width: '100%', }, svg: { width: '100%', height: 300, }, snapshot: { fill: 'gray', width: SNAPSHOT_SIZE, height: SNAPSHOT_SIZE, }, snapshotPassed: { fill: 'green', }, snapshotFailed: { fill: 'red', }, }
actor-apps/app-web/src/app/components/ToolbarSection.react.js
sc4599/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin } from 'react-intl'; import classnames from 'classnames'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import DialogStore from 'stores/DialogStore'; import ActivityStore from 'stores/ActivityStore'; //import AvatarItem from 'components/common/AvatarItem.react'; const getStateFromStores = () => { return { dialogInfo: DialogStore.getSelectedDialogInfo(), isActivityOpen: ActivityStore.isOpen() }; }; @ReactMixin.decorate(IntlMixin) class ToolbarSection extends React.Component { state = { dialogInfo: null, isActivityOpen: false }; constructor(props) { super(props); DialogStore.addSelectedChangeListener(this.onChange); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeSelectedChangeListener(this.onChange); ActivityStore.removeChangeListener(this.onChange); } onClick = () => { if (!this.state.isActivityOpen) { ActivityActionCreators.show(); } else { ActivityActionCreators.hide(); } }; onChange = () => { this.setState(getStateFromStores()); }; render() { const info = this.state.dialogInfo; const isActivityOpen = this.state.isActivityOpen; let infoButtonClassName = classnames('button button--icon', { 'button--active': isActivityOpen }); if (info != null) { return ( <header className="toolbar"> <div className="pull-left"> <div className="toolbar__peer row"> <div className="toolbar__peer__body col-xs"> <span className="toolbar__peer__title">{info.name}</span> <span className="toolbar__peer__presence">{info.presence}</span> </div> </div> </div> <div className="toolbar__controls pull-right"> <div className="toolbar__controls__search pull-left hide"> <i className="material-icons">search</i> <input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/> </div> <div className="toolbar__controls__buttons pull-right"> <button className={infoButtonClassName} onClick={this.onClick}> <i className="material-icons">info</i> </button> <button className="button button--icon hide"> <i className="material-icons">more_vert</i> </button> </div> </div> </header> ); } else { return ( <header className="toolbar"> </header> ); } } } export default ToolbarSection;
src/components/Taf/ChangeGroup.spec.js
maartenlterpstra/GeoWeb-FrontEnd
import React from 'react'; import ChangeGroup from './ChangeGroup'; import { mount } from 'enzyme'; describe('(Container) Taf/ChangeGroup.jsx', () => { it('Renders a ChangeGroup', () => { const _component = mount(<ChangeGroup value={{}} />); expect(_component.type()).to.eql(ChangeGroup); }); });
src/destinations/render.js
RoyalIcing/gateau
import R from 'ramda' import React from 'react' import { Seed } from 'react-seeds' const resolveContentIn = R.curry(function resolveItemIn(source, path) { //path = R.filter(R.isNil) console.log('resolveContentIn', path, source) path = R.insertAll(1, ['content'], path) return R.path(path, source) }) const variationForItemIn = R.curry(function adjustItemIn(source, path) { const id = R.head(path) return R.path([id, 'variationReference'], source) }) const resolveContentUsing = (ingredients) => { const resolveIngredientReference = resolveContentIn(ingredients) const variationForPath = variationForItemIn(ingredients) return (value, { single = true, set, alter } = {}) => { if (R.isNil(value)) { return } else if (value.mentions != null && value.mentions.length > 0 && value.mentions[0] != null) { console.log('MENTIONS', { set, alter }) if (set) { R.forEach( (item) => item.set(set), result ) } else if (alter) { const path = value.mentions[0] const variation = variationForPath(path) console.log('altering variation', variation) const innerPath = R.tail(path) variation.adjustPath(innerPath, alter) } else { console.log('RESOLVE', value.mentions) const resolved = R.map(resolveIngredientReference, value.mentions) console.log('RESOLVED', resolved) if (resolved == null) { return } return single ? resolved[0] : resolved } } else if (value.texts != null) { return value.texts } else { return value } } } function elementFromText(text) { return { text, references: [], tags: {}, children: [] } } export const renderElement = ({ ingredients, elementRendererForTags }) => { const resolveContent = resolveContentUsing(ingredients) const extra = { elementFromText } const Element = R.converge( R.call, [ R.pipe( R.props(['defaultTags', 'tags']), R.apply(R.mergeWith(R.merge)), elementRendererForTags ), R.prop('mentions'), R.prop('texts'), R.prop('children'), (ignore) => Element, // Have to put in closure as it is currently being assigned R.always(resolveContent), R.always(extra) ] ) Element.renderArray = (options, array) => ( array.map((element, index) => ( <Element key={ index } { ...options } { ...element } /> )) ) return Element } export const DefaultSection = ({ children }) => ( <Seed Component='section' //column margin={{ base: '2rem', top: 0 }} children={ children } /> ) export const DefaultMaster = ({ children }) => ( <Seed padding={{ top: '1rem' }} children={ children } /> ) export const renderTreeUsing = ({ elementRendererForTags, Section = DefaultSection, Master = DefaultMaster }) => ({ ingredients, contentTree }) => { // FIXME: use valueForIngredient instead that encapsulates ingredientVariationIndexes const Element = renderElement({ ingredients, elementRendererForTags }) return ( <Master ingredients={ ingredients }> { contentTree.map((section, sectionIndex) => ( <Section key={ sectionIndex }> { section.map((element, elementIndex) => ( <Element key={ elementIndex } { ...element } /> )) } </Section> )) } </Master> ) }
src/svg-icons/av/repeat.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRepeat = (props) => ( <SvgIcon {...props}> <path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/> </SvgIcon> ); AvRepeat = pure(AvRepeat); AvRepeat.displayName = 'AvRepeat'; AvRepeat.muiName = 'SvgIcon'; export default AvRepeat;
index.js
techiesanchez/rythus-app
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import createLogger from 'redux-logger'; import thunkMiddleware from 'redux-thunk'; import reducers from './reducers'; import { RythusCardsApp } from './components/App'; const middleware = [ thunkMiddleware ]; if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()); } var initialState = { displayedCard: {}, selectedItem: "Encounter", menuItems: [ { name: 'resourcez', active: false }, { name: 'settlementz', active: false }, { name: 'battallionz', active: false }, { name: 'heroz', active: false }, { name: 'merchantz', active: false }, { name: 'dungeonz', active: false }, { name: 'villainz', active: false }, { name: 'monsterz', active: false }, { name: 'encounterz', active: false }, { name: 'rewardz', active: false } ], isFetching: false, cards: {}, discards: {} } var store = createStore(reducers, initialState, applyMiddleware(...middleware)); render( <Provider store={store}> <RythusCardsApp /> </Provider>, document.getElementById('appy') );
src/client/routes.js
obimod/este
import App from './app/app.react'; import Home from './home/index.react'; import Login from './auth/index.react'; import Me from './me/index.react'; import NotFound from './components/notfound.react'; import React from 'react'; import Todos from './todos/index.react'; import {DefaultRoute, NotFoundRoute, Route} from 'react-router'; export default ( <Route handler={App} path="/"> <DefaultRoute handler={Home} name="home" /> <NotFoundRoute handler={NotFound} name="not-found" /> <Route handler={Login} name="login" /> <Route handler={Me} name="me" /> <Route handler={Todos} name="todos" /> </Route> );
stories/index.js
ionutmilica/react-chartjs-components
import React from 'react'; import './ComponentsExample';
src/svg-icons/communication/message.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationMessage = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/> </SvgIcon> ); CommunicationMessage = pure(CommunicationMessage); CommunicationMessage.displayName = 'CommunicationMessage'; export default CommunicationMessage;
ScrollableTabView自定义TarBar/index.android.js
yuanliangYL/ReactNative-Components-Demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class ScrollableTabView extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ScrollableTabView', () => ScrollableTabView);
src/encoded/static/components/viz/FourfrontLogo.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import * as d3 from 'd3'; /** Renders out the 4DN Logo SVG as a React element(s) */ export class FourfrontLogo extends React.PureComponent { static defaultProps = { 'id' : "fourfront_logo_svg", 'circlePathDefinitionOrig' : "m1,30c0,-16.0221 12.9779,-29 29,-29c16.0221,0 29,12.9779 29,29c0,16.0221 -12.9779,29 -29,29c-16.0221,0 -29,-12.9779 -29,-29z", 'circlePathDefinitionHover' : "m3.33331,34.33326c-2.66663,-17.02208 2.97807,-23.00009 29.99997,-31.33328c27.02188,-8.33321 29.66667,22.31102 16.6669,34.66654c-12.99978,12.35552 -15.64454,20.00017 -28.66669,19.00018c-13.02214,-0.99998 -15.33356,-5.31137 -18.00018,-22.33344z", 'textTransformOrig' : "translate(9, 37)", 'textTransformHover' : "translate(48, 24) scale(0.2, 0.6)", 'fgCircleTransformOrig' : "translate(50, 20) scale(0.35, 0.35) rotate(-135)", 'fgCircleTransformHover' : "translate(36, 28) scale(0.7, 0.65) rotate(-135)", 'hoverDelayUntilTransform' : 400, 'title' : "Data Portal" }; static svgElemStyle = { 'verticalAlign' : 'middle', 'display' : 'inline-block', 'height' : '100%', 'paddingBottom' : 10, 'paddingTop' : 10, 'transition' : "padding .3s, transform .3s", 'maxHeight' : 80 }; static svgBGCircleStyle = { 'fill' : "url(#fourfront_linear_gradient)", "stroke" : "transparent", "strokeWidth" : 1 }; static svgTextStyleOut = { 'transition' : "letter-spacing 1s, opacity .7s, stroke .7s, stroke-width .7s, fill .7s", 'fontSize' : 23, 'fill' : '#fff', 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'stroke' : 'transparent', 'strokeWidth' : 0, 'strokeLinejoin' : 'round', 'opacity' : 1, 'letterSpacing' : 0 }; static svgTextStyleIn = { 'transition' : "letter-spacing 1s .4s linear, opacity .7s .4s, stroke .7s 4s, stroke-width .7s 4s, fill .7s .4s", 'letterSpacing' : -14, 'stroke' : 'rgba(0,0,0,0.2)', 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15 }; static svgInnerCircleStyleOut = { 'transition': "opacity 1.2s", 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15, 'stroke' : 'rgba(0,0,0,0.2)', 'fontSize' : 23, 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'strokeLinejoin' : 'round' }; static svgInnerCircleStyleIn = { 'transition': "opacity 1.2s .6s", 'opacity' : 1 }; constructor(props){ super(props); this.setHoverStateOnDoTiming = _.throttle(this.setHoverStateOnDoTiming.bind(this), 1000); this.setHoverStateOn = this.setHoverStateOn.bind(this); this.setHoverStateOff = this.setHoverStateOff.bind(this); this.svgRef = React.createRef(); this.bgCircleRef = React.createRef(); this.fgTextRef = React.createRef(); this.fgCircleRef = React.createRef(); this.state = { hover : false }; } setHoverStateOn(e){ this.setState({ 'hover': true }, this.setHoverStateOnDoTiming); } setHoverStateOnDoTiming(e){ const { circlePathDefinitionHover, textTransformHover, fgCircleTransformHover, hoverDelayUntilTransform } = this.props; // CSS styles controlled via stylesheets setTimeout(()=>{ const { hover } = this.state; if (!hover) return; // No longer hovering. Cancel. d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionHover); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(700) .attr('transform', textTransformHover); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1200) .attr('transform', fgCircleTransformHover); }, hoverDelayUntilTransform); } setHoverStateOff(e){ const { circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig } = this.props; this.setState({ 'hover' : false }, ()=>{ d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionOrig); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(1200) .attr('transform', textTransformOrig); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('transform', fgCircleTransformOrig); }); } renderDefs(){ return ( <defs> <linearGradient id="fourfront_linear_gradient" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238bae"/> <stop offset="1" stopColor="#8ac640"/> </linearGradient> <linearGradient id="fourfront_linear_gradient_darker" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238b8e"/> <stop offset="1" stopColor="#8aa640"/> </linearGradient> </defs> ); } render(){ const { id, circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig, onClick, title } = this.props; const { hover } = this.state; return ( <div className={"img-container" + (hover ? " is-hovering" : "")} onClick={onClick} onMouseEnter={this.setHoverStateOn} onMouseLeave={this.setHoverStateOff}> <svg id={id} ref={this.svgRef} viewBox="0 0 60 60" style={FourfrontLogo.svgElemStyle}> { this.renderDefs() } <path d={circlePathDefinitionOrig} style={FourfrontLogo.svgBGCircleStyle} ref={this.bgCircleRef} /> <text transform={textTransformOrig} style={hover ? { ...FourfrontLogo.svgTextStyleOut, ...FourfrontLogo.svgTextStyleIn } : FourfrontLogo.svgTextStyleOut} ref={this.fgTextRef}> 4DN </text> <text transform={fgCircleTransformOrig} style={hover ? { ...FourfrontLogo.svgInnerCircleStyleOut, ...FourfrontLogo.svgInnerCircleStyleIn } : FourfrontLogo.svgInnerCircleStyleOut} ref={this.fgCircleRef}> O </text> </svg> <span className="navbar-title">Data Portal</span> </div> ); } }
server/frontend/components/Header/Header.js
SchadkoAO/FDTD_Solver
import React from 'react'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; export const Header = ({ children }) => ( <AppBar position="static"> <Toolbar> <IconButton color="contrast" aria-label="Menu"> <MenuIcon /> </IconButton> <Typography type="title" color="inherit"> FDTD Solver </Typography> </Toolbar> </AppBar> ); export default Header;
src/js/components/Gallery/GalleryImage.js
jamieallen59/jamieallen
import React from 'react' import PropTypes from 'prop-types' import CSSModules from 'react-css-modules' import styles from './Gallery.less' import { className } from './Gallery' const GalleryImage = ({ imageUrl, onClick, display = true }) => ( <div onClick={onClick} > <img styleName={display ? `${className}__image` : `${className}__image ${className}__image--hidden`} // eslint-disable-line max-len src={imageUrl} role='presentation' /> </div> ) GalleryImage.propTypes = { display: PropTypes.bool, imageUrl: PropTypes.string, onClick: PropTypes.func } export default CSSModules(GalleryImage, styles, { allowMultiple: true })
docs/src/examples/elements/Input/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Types from './Types' import States from './States' import Variations from './Variations' import Usage from './Usage' const InputExamples = () => ( <div> <Types /> <States /> <Variations /> <Usage /> </div> ) export default InputExamples
src/Parser/Hunter/BeastMastery/Modules/Talents/DireFrenzy.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import STATISTIC_ORDER from 'Main/STATISTIC_ORDER'; import { formatPercentage } from 'common/format'; import StatisticBox from 'Main/StatisticBox'; import ItemDamageDone from 'Main/ItemDamageDone'; import Wrapper from 'common/Wrapper'; /* * Dire Frenzy * Causes your pet to enter a frenzy, performing a flurry of 5 attacks on the target, * and gaining 30% increased attack speed for 8 sec, stacking up to 3 times. */ //max stacks pet can have of Dire Frenzy buff const MAX_DIRE_FRENZY_STACKS = 3; const DIRE_FRENZY_DURATION = 8000; class DireFrenzy extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; buffStart = 0; buffEnd = 0; currentStacks = 0; startOfMaxStacks = 0; timeAtMaxStacks = 0; timeBuffed = 0; lastDireFrenzyCast = null; timeCalculated = null; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.lastDireFrenzyCast = event.timestamp; } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_DAMAGE.id) { return; } this.damage += event.amount + (event.absorbed || 0); } on_toPlayerPet_removebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.timeBuffed += event.timestamp - this.buffStart; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.timeAtMaxStacks += event.timestamp - this.startOfMaxStacks; } this.currentStacks = 0; this.timeCalculated = true; } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } if (this.currentStacks > 0) { this.timeBuffed += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.buffStart; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.timeAtMaxStacks += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.startOfMaxStacks; } } this.buffStart = event.timestamp; this.currentStacks = 1; this.timeCalculated = false; } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.currentStacks = event.stack; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.startOfMaxStacks = event.timestamp; } } on_finished() { if (!this.timeCalculated) { if ((this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) > this.owner.fight.end_time) { if (this.currentStacks > 0) { this.timeBuffed += this.owner.fight.end_time - this.buffStart; } if (this.currentStacks === 3) { this.timeAtMaxStacks += this.owner.fight.end_time - this.startOfMaxStacks; } } else { if (this.currentStacks > 0) { this.timeBuffed += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.buffStart; } if (this.currentStacks === 3) { this.timeAtMaxStacks += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.startOfMaxStacks; } } } } get percentUptimeMaxStacks() { return this.timeAtMaxStacks / this.owner.fightDuration; } get percentUptimePet() { return this.timeBuffed / this.owner.fightDuration; } get percentPlayerUptime() { //This calculates the uptime over the course of the encounter of Dire Frenzy for the player return (this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_1.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_2.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_3.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_4.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_5.id)) / this.owner.fightDuration; } get direFrenzyUptimeThreshold() { return { actual: this.percentUptimePet, isLessThan: { minor: 0.85, average: 0.75, major: 0.7, }, style: 'percentage', }; } get direFrenzy3StackThreshold() { return { actual: this.percentUptimeMaxStacks, isLessThan: { minor: 0.45, average: 0.40, major: 0.35, }, style: 'percentage', }; } suggestions(when) { when(this.direFrenzyUptimeThreshold) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your pet has a general low uptime of the buff from <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} icon />, you should never be sitting on 2 stacks of this spells, if you've chosen this talent, it's your most important spell to continously be casting. </Wrapper>) .icon(SPELLS.DIRE_FRENZY_TALENT.icon) .actual(`Your pet had the buff from Dire Frenzy for ${actual}% of the fight`) .recommended(`${recommended}% is recommended`); }); when(this.direFrenzy3StackThreshold).addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your pet has a general low uptime of the 3 stacked buff from <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} icon />. It's important to try and maintain the buff at 3 stacks for as long as possible, this is done by spacing out your casts, but at the same time never letting them cap on charges. </Wrapper>) .icon(SPELLS.DIRE_FRENZY_TALENT.icon) .actual(`Your pet had 3 stacks of the buff from Dire Frenzy for ${actual}% of the fight`) .recommended(`${recommended}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.DIRE_FRENZY_TALENT.id} />} value={`${formatPercentage(this.percentUptimeMaxStacks)}%`} label={`3 Stack Uptime`} tooltip={`Your pet had an overall uptime of ${formatPercentage(this.percentUptimePet)}% on the increased attack speed buff <br/> You had an uptime of ${formatPercentage(this.percentPlayerUptime)}% on the focus regen buff, this number indicates you had an average of ${(this.percentPlayerUptime).toFixed(2)} stacks of the buff up over the course of the encounter`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(5); subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id}> <SpellIcon id={SPELLS.DIRE_FRENZY_TALENT.id} noLink /> Dire Frenzy </SpellLink> </div> <div className="flex-sub text-right"> <ItemDamageDone amount={this.damage} /> </div> </div> ); } } export default DireFrenzy;