path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
docs/app/Examples/elements/Button/Variations/ButtonSocialExample.js
jcarbo/stardust
import React from 'react' import { Button, Icon } from 'stardust' const ButtonSocialExample = () => ( <div> <Button color='facebook'> <Icon name='facebook' /> Facebook </Button> <Button color='twitter'> <Icon name='twitter' /> Twitter </Button> <Button color='google plus'> <Icon name='google plus' /> Google Plus </Button> <Button color='vk'> <Icon name='vk' /> VK </Button> <Button color='linkedin'> <Icon name='linkedin' /> LinkedIn </Button> <Button color='instagram'> <Icon name='instagram' /> Instagram </Button> <Button color='youtube'> <Icon name='youtube' /> YouTube </Button> </div> ) export default ButtonSocialExample
src/containers/Asians/Registration/Institutions/StatusNotice/AcceptedInstance/index.js
westoncolemanl/tabbr-web
import React from 'react' import withStyles from 'material-ui/styles/withStyles' import Card, { CardHeader, CardContent } from 'material-ui/Card' import * as utils from 'utils' const styles = theme => ({ body: { marginBottom: theme.spacing.unit } }) export default withStyles(styles)(({ registrationInstitution, classes }) => <Card className={classes.body} > <CardHeader title={`${registrationInstitution.name} (${registrationInstitution.country})`} subheader={`${utils.constants.status[registrationInstitution.status]}`} /> <CardContent> {'Your registration is accepted. Should you want to withdraw your registration, you will need to send a request to the organizing committee.'} </CardContent> </Card> )
src/scripts/components/TodoHeader.js
fantasywind/React-Todo
import React from 'react'; import {Link} from 'react-router-component'; import CollapseControl from './CollapseControl.js'; import ToDoCreator from './ToDoCreator.js'; const styles = { wrap: { display: 'flex', height: 60, lineHeight: '60px', borderBottom: '1px solid #aaa' } }; const TodoHeader = React.createClass({ render() { return ( <div style={styles.wrap}> <CollapseControl isCollapsed={this.props.isCollapsed} toggleCollapse={this.props.toggleCollapse} /> <ToDoCreator /> </div> ) } }); module.exports = TodoHeader;
src/prisonBreak/commandProcessor.js
link1900/linkin-games
// @flow import React from 'react'; import Chance from 'chance'; import { includes, first, find, filter, intersection, isNil, tail, isEmpty } from 'lodash'; import './commandLine.css'; import CommandRef from './CommandRef'; import type { PrisonBreakStore } from './PrisonBreakReducer'; import { convertToDirection, flipDirection } from './Location'; import { createWorld, itemsAtLocation, monstersAtLocation } from './World'; import type { Location } from './Location'; import type { Entity } from './Entity'; import type { Item } from './Item'; import { equipmentTypes } from './Item'; import { getPlayerLocation, getPlayer, getPlayerScore } from './Player'; import type { Creature } from './Creature'; const chance = new Chance(); type CommandDef = { keys: Array<string>, action?: Function, hidden?: boolean, adverb?: boolean }; const commandList: Array<CommandDef> = [ { keys: ['look', 'l', 'where', 'ls'], action: look }, { keys: ['north', 'n', 'up'], action: move }, { keys: ['east', 'e', 'right'], action: move }, { keys: ['west', 'w', 'left'], action: move }, { keys: ['south', 's', 'down'], action: move }, { keys: ['move', 'go'], action: moveBy }, { keys: ['clear'], action: clear }, { keys: ['help', '?'], action: help }, { keys: ['quest', 'log', 'journal', 'goal', 'objective', 'load'], action: quest }, { keys: ['save', 'backup'], action: save }, { keys: ['restart', 'reset', 'delete'], action: restart }, { keys: ['yes', 'ok', 'agree', 'nod'], action: yes }, { keys: ['no', 'nope', 'disagree'], action: no }, { keys: ['status', 'me', 'self', 'stats'], action: status }, { keys: ['inventory'], action: inventory }, { keys: ['equipment'], action: equipment }, { keys: ['take', 'grab', 'get', 'pickup', 'collect'], action: take }, { keys: ['list'], adverb: true }, { keys: ['equip', 'wear', 'don'], action: equip }, { keys: ['unequip', 'remove', 'doff'], action: unequip }, { keys: ['open', 'unlock'], action: unlock }, { keys: ['showmap'], action: revealMap, hidden: true }, { keys: ['attack', 'kill', 'damage', 'hurt', 'stab', 'kick', 'slice', 'chop'], action: attack }, { keys: ['use', 'drink', 'consume', 'eat'], action: use } // drop //item discard // quit //game //exit ]; export function processCommand(state: PrisonBreakStore, command: string, allowedCommands?: Array<string>) { const commandWords = command.split(' '); const firstWord = first(commandWords); if (!isAllowedCommand(firstWord, allowedCommands)) { return invalidInput(state, command); } const commandDef = find(commandList, cd => includes(cd.keys, firstWord)); if (!commandDef) { return error(state, command); } if (commandDef.adverb) { const rest = tail(commandWords).join(' '); return processCommand(state, rest); } return commandDef.action(state, command); } export function logViewProcessor(logItem: any) { return logItem; } export function updateLog(state: PrisonBreakStore, command: string, value: any) { return { ...state, currentInput: '', log: state.log.concat([command]).concat([value]), history: state.history.concat([command]), historyPosition: state.history.length + 1 }; } export function updateLogDirect(state: PrisonBreakStore, value: any) { return { ...state, log: state.log.concat([value]) }; } export function clear(state: PrisonBreakStore) { return { ...state, currentInput: '', log: [] }; } export function error(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> Sorry I do not understand {command}. Try entering <CommandRef command="help" /> or <CommandRef command="?" /> to see a list of commands. </span> ); } export function look(state: PrisonBreakStore, command: string) { const playerLocation = getPlayerLocation(state); if (!playerLocation) { return updateLog(state, command, <span>You are located no where</span>); } return updateLog( state, command, <span> You are located at <b>{playerLocation.name}</b>. {playerLocation.description} <br /> Looking around you see:<br /> {possibleDirections(state, playerLocation)} {itemLook(state, playerLocation)} {monsterLook(state, playerLocation)} </span> ); } function itemLook(state: PrisonBreakStore, location: Location) { const items = itemsAtLocation(state, location); if (items.length === 0) { return null; } return ( <span> You can see the following item{items.length === 1 ? '' : 's'}: <ul> {items.map(item => (<li key={item.id}> <CommandRef command={`take ${item.name}`} label={item.name} /> </li>))} </ul> </span> ); } function monsterLook(state: PrisonBreakStore, location: Location) { const monsters = monstersAtLocation(state, location); if (monsters.length === 0) { return null; } return ( <span> You can see the following enemies: <ul> {monsters.map(monster => (<li key={monster.id}> <CommandRef command={`attack ${monster.name}`} label={monster.name} /> </li>))} </ul> </span> ); } function possibleDirections(state, location) { if (location.paths.length === 0) { return null; } return ( <span> You can move in the following direction{location.paths.length === 1 ? '' : 's'}: <ul> {location.paths.map((path) => { if (!path) return null; const newLocation = find(state.world.locations, { id: path.toLocationId }); return ( <li key={path.direction}> <CommandRef command={path.direction} /> to {newLocation.name} </li> ); })} </ul> </span> ); } export function help(state: PrisonBreakStore, command: string) { const commandKeys = commandList.filter(cl => cl.hidden !== true).map(commandDef => first(commandDef.keys)); return updateLog( state, command, <span> To play this game you enter your actions by typing in the command such as <CommandRef command="north" /> to move north or <CommandRef command="look" /> to look around.<br /> Here is the list of valid commands:<br /> <ul> {commandKeys.sort().map((key) => { return ( <li key={key}> <CommandRef command={key} /> </li> ); })} </ul> </span> ); } export function newline(state: PrisonBreakStore) { return updateLogDirect(state, <br />); } export function intro(state: PrisonBreakStore) { return updateLogDirect( state, <span> You wake up in your cell as you have done for the past few weeks, but today something is different. Your cell door is open! This is your one chance to escape this prison. I need to move <CommandRef command="south" /> and get out of this cell. </span> ); } export function move(state: PrisonBreakStore, command: string) { const direction = convertToDirection(command); if (!direction) { return updateLog(state, command, <span>You cannot move in that direction</span>); } const playerLocation = getPlayerLocation(state); const player = getPlayer(state); if (!player || !playerLocation || !playerLocation.paths) { return updateLog( state, command, <span> You cannot move <CommandRef command={direction} />, there is no path that way. </span> ); } const path = playerLocation.paths.find(p => p.direction === direction); if (!path) { return updateLog( state, command, <span> You cannot move <CommandRef command={direction} />, there is no path that way. </span> ); } if (path.locked) { return updateLog( state, command, <span> The door in that direction is locked. I will need a key to <CommandRef command="unlock" /> it. </span> ); } const monsters = monstersAtLocation(state, playerLocation); if (monsters.length > 0) { return updateLog( state, command, <span> {first(monsters).name} blocks our path. I will have to <CommandRef command={`attack ${first(monsters).name}`} label="attack" /> and defeat it first. </span> ); } let updatedState = updateEntity(state, player.id, 'locationId', path.toLocationId); const oldLocation = find(state.world.locations, { id: path.fromLocationId }); const newLocation = find(state.world.locations, { id: path.toLocationId }); updatedState = updateLocation(updatedState, newLocation.id, 'visited', true); updatedState = updateLog( updatedState, command, <span> You moved from <b>{oldLocation.name}</b> into <b>{newLocation.name}</b>.<br /> </span> ); return look(updatedState, 'look'); } export function moveBy(state: PrisonBreakStore, command: string) { const directionParts = command.split(' '); if (directionParts.length === 2) { const direction = directionParts[1]; return move(state, direction); } else { return updateLog(state, command, <span>What direction should I move in?</span>); } } export function quest(state: PrisonBreakStore, command: string) { if (state.world.quest === 'main') { return updateLog( state, command, <span> I need to <CommandRef command="look" /> around for an escape. </span> ); } if (state.world.quest === 'done') { return updateLog(state, command, <span>I am free at last.</span>); } const updatedState = { ...state, world: { ...state.world, quest: 'main' } }; return updateLog( updatedState, command, <span> You wake up in your cell as you have done for the past few weeks, but today something is different. Your cell door is open! This is your one chance to escape this prison. I need to move <CommandRef command="south" /> and get out of this cell. </span> ); } function save(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> This game auto saves all progress. If you would like to start from the beginning use the <CommandRef command="restart" /> command. </span> ); } function restart(state: PrisonBreakStore, command: string) { const updateState = { ...state, prompt: { onYes: resetWorld, onNo: (someState: PrisonBreakStore) => { const otherUpdateState = { ...someState, prompt: null }; return updateLog(otherUpdateState, command, <span>You continue on.</span>); } } }; return updateLog( updateState, command, <span> Are you sure you want to <CommandRef command="restart" /> from the beginning? All saved progress up to this point will be lost. (<CommandRef command="yes" /> /{' '} <CommandRef command="no" />) </span> ); } function resetWorld(state: PrisonBreakStore, command: string) { const updateState = { ...state, prompt: null, world: createWorld() }; return updateLog( updateState, command, <span> Save cleared. You can now <CommandRef command="load" />. </span> ); } function yes(state: PrisonBreakStore, command: string) { if (state.prompt) { return state.prompt.onYes(state, command); } else { return updateLog(state, command, <span>Yes to what?</span>); } } function no(state: PrisonBreakStore, command: string) { if (state.prompt) { return state.prompt.onNo(state, command); } else { return updateLog(state, command, <span>No to what?</span>); } } function invalidInput(state: PrisonBreakStore, command: string) { return updateLog( state, command, <span> You must answer either <CommandRef command="yes" /> or <CommandRef command="no" /> </span> ); } function isAllowedCommand(command: string, allowedCommands: ?Array<string>) { if (!allowedCommands) { return true; } const commandWords = command.split(' '); const firstWord = first(commandWords); const allowedCommandList = filter(commandList, commandDef => intersection(commandDef.keys, allowedCommands).length > 0); return !isNil(find(allowedCommandList, commandDef => includes(commandDef.keys, firstWord))); } function status(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } const stats = [ { name: 'HP', value: `${player.currentHP} / ${player.maxHP}` }, { name: 'Strength', value: player.strength }, { name: 'Resistance', value: player.resistance }, { name: 'Speed', value: player.speed }, { name: 'Attack', value: player.attack }, { name: 'Defence', value: player.defence } ]; return updateLog( state, command, <span> My current status is:<br /> {stats.map(stat => (<span key={stat.name}> {stat.name}: {` ${stat.value}`} <br /> </span>))} {playerInventory(state)} {playerEquipment(state)} </span> ); } function inventory(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } return updateLog( state, command, <span> {playerInventory(state)} </span> ); } function equipment(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return updateLog(state, command, <span>I am nothing</span>); } return updateLog( state, command, <span> {playerEquipment(state)} </span> ); } function playerInventory(state: PrisonBreakStore) { const playerItems = getPlayerItems(state); if (playerItems.length < 1) { return null; } return ( <p> {"I'm"} currently carrying: <br /> {playerItems.map(itemText)} </p> ); } function itemText(item: Item) { return ( <span key={item.id}> {itemName(item)} - {item.description} <br /> </span> ); } function itemName(item: Item) { const isEquipment = includes(equipmentTypes, item.type); if (isEquipment) { return <CommandRef command={`equip ${item.name}`} label={item.name} />; } else { return item.name; } } function playerEquipment(state: PrisonBreakStore) { const items = getPlayerEquipment(state); if (items.length < 1) { return null; } return ( <p> {"I'm"} currently holding: <br /> {items.map((item) => { return ( <span key={item.id}> {item.name} - {item.description} <br /> </span> ); })} </p> ); } function take(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const location = getPlayerLocation(state); const items = itemsAtLocation(state, location); const foundItem = find(items, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); const player = getPlayer(state); if (!foundItem || !player) { return updateLog( state, command, <span> Cannot find anything called {commandTail} </span> ); } let updateState = updateEntity(state, foundItem.id, 'locationId', null); updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.concat(foundItem.id)); updateState = updateLog( updateState, command, <span> You have taken {foundItem.name} </span> ); if (includes(equipmentTypes, foundItem.type)) { return equip(updateState, `equip ${foundItem.name}`); } return updateState; } export function updateEntity(state: PrisonBreakStore, id: string, field: string, value: any): PrisonBreakStore { const entity = find(state.world.entities, { id }); if (!entity) { return state; } const updatedEntity = { ...entity, [field]: value }; return updateEntityForState(state, updatedEntity); } export function updateLocation(state: PrisonBreakStore, id: string, field: string, value: any): PrisonBreakStore { const location = find(state.world.locations, { id }); if (!location) { return state; } const updateLoc = { ...location, [field]: value }; return updateLocationForState(state, updateLoc); } export function updateLocationForState(state: PrisonBreakStore, location: Location): PrisonBreakStore { return { ...state, world: { ...state.world, locations: state.world.locations.filter(e => e.id !== location.id).concat(location) } }; } export function updateEntityForState(state: PrisonBreakStore, entity: Entity): PrisonBreakStore { return { ...state, world: { ...state.world, entities: state.world.entities.filter(e => e.id !== entity.id).concat(entity) } }; } function equip(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const playerItems = getPlayerItems(state); const player = getPlayer(state); const foundItem = find(playerItems, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot equip {commandTail} as it is not in your inventory. </span> ); } if (!includes(equipmentTypes, foundItem.type)) { return updateLog( state, command, <span> {commandTail} cannot be equipped. </span> ); } let updateState = state; if (foundItem.type === 'weapon') { updateState = updateEntity(updateState, player.id, 'weaponId', foundItem.id); updateState = updateEntity(updateState, player.id, 'attack', player.attack + foundItem.attackChange); } if (foundItem.type === 'shield') { updateState = updateEntity(updateState, player.id, 'shieldId', foundItem.id); updateState = updateEntity(updateState, player.id, 'defence', player.defence + foundItem.defenceChange); } updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.filter(itemId => itemId !== foundItem.id)); return updateLog( updateState, command, <span> You have equipped {foundItem.name} </span> ); } function unequip(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const pe = getPlayerEquipment(state); const player = getPlayer(state); const foundItem = find(pe, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot un-equip {commandTail} as it is not equipped. </span> ); } let updateState = state; if (foundItem.type === 'weapon') { updateState = updateEntity(updateState, player.id, 'weaponId', null); updateState = updateEntity(updateState, player.id, 'attack', player.attack - foundItem.attackChange); } if (foundItem.type === 'shield') { updateState = updateEntity(updateState, player.id, 'shieldId', null); updateState = updateEntity(updateState, player.id, 'defence', player.defence - foundItem.defenceChange); } updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.concat(foundItem.id)); return updateLog( updateState, command, <span> You have un-equipped {foundItem.name} </span> ); } function getPlayerItems(state: PrisonBreakStore): Array<Item> { const player = getPlayer(state); if (!player) { return []; } return player.itemIds.map(itemId => find(state.world.entities, { id: itemId })); } function getPlayerEquipment(state: PrisonBreakStore): Array<Item> { const player = getPlayer(state); if (!player) { return []; } const e = []; const weapon = find(state.world.entities, { id: player.weaponId }); const shield = find(state.world.entities, { id: player.shieldId }); if (weapon) { e.push(weapon); } if (shield) { e.push(shield); } return e; } export function unlock(state: PrisonBreakStore, command: string) { const currentLocation = getPlayerLocation(state); if (!currentLocation) { return updateLog(state, command, <span>What door</span>); } const lockedPaths = currentLocation.paths.filter(p => p.locked); if (lockedPaths === 0) { return updateLog(state, command, <span>There are no locked doors here.</span>); } const connectedLocations = lockedPaths.map(p => find(state.world.locations, { id: p.toLocationId })); let allowedDirection = ''; const updatePaths = currentLocation.paths.map((p) => { if (!p.locked) { return p; } allowedDirection = flipDirection(p.direction); return { ...p, locked: false }; }); let updateState = updateLocation(state, currentLocation.id, 'paths', updatePaths); connectedLocations.forEach((loc) => { const otherPaths = loc.paths.map((poa) => { if (!poa.locked || poa.direction !== allowedDirection) { return poa; } return { ...poa, locked: false }; }); updateState = updateLocation(updateState, loc.id, 'paths', otherPaths); }); return updateLog(updateState, command, <span>You have unlocked all doors.</span>); } export function revealMap(state: PrisonBreakStore, command: string) { let updatedState = state; state.world.locations.forEach((location) => { updatedState = updateLocation(updatedState, location.id, 'visited', true); }); return updateLog(updatedState, command, <span>Map is revealed.</span>); } export function attack(state: PrisonBreakStore, command: string) { const player = getPlayer(state); if (!player) { return null; } const playerLocation = getPlayerLocation(state); const monsters = monstersAtLocation(state, playerLocation); if (isEmpty(monsters)) { return updateLog(state, command, <span>There is nothing you can attack in here.</span>); } const monster = first(monsters); return battle(state, command, player, monster); } export function battle(state: PrisonBreakStore, command: string, creature1: Creature, creature2: Creature) { // fastest creature goes first const fighters = [creature1, creature2].sort((c1, c2) => (c2.speed + (c2.speed / 4)) - (c1.speed + (c1.speed / 4))); const fighter1 = fighters[0]; const fighter2 = fighters[1]; let updateState = updateLog( state, command, <span> {fighter1.name} attacks {fighter2.name} </span> ); // first attack updateState = damage(updateState, fighter1, fighter2); updateState = updateLogDirect( updateState, <span> {fighter1.name} HP: {fighter1.currentHP}/{fighter1.maxHP} vs. {fighter2.name} HP: {fighter2.currentHP}/{fighter2.maxHP} </span> ); // check for win/loss condition if (fighter2.currentHP <= 0) { return finishBattle(updateState, fighter1, fighter2); } // counter attack updateState = damage(updateState, fighter2, fighter1); // check for win/loss condition if (fighter1.currentHP <= 0) { return finishBattle(updateState, fighter2, fighter1); } // final status update return updateLogDirect( updateState, <span> {fighter1.name} HP: {fighter1.currentHP}/{fighter1.maxHP} vs. {fighter2.name} HP: {fighter2.currentHP}/{fighter2.maxHP} </span> ); } export function damage(state: PrisonBreakStore, creature1: Creature, creature2: Creature) { const attackBoost = Math.round(creature1.attack * 0.25); const att = creature1.attack + attackBoost + chance.natural({ min: 0, max: attackBoost }); const damageAmount = att - creature2.defence; creature2.currentHP -= damageAmount; if (creature2.currentHP < 0) { creature2.currentHP = 0; } const updateState = updateEntity(state, creature2.id, 'currentHP', creature2.currentHP); return updateLogDirect( updateState, <span> {creature1.name} attacked {creature2.name} for {damageAmount} damage! </span> ); } export function finishBattle(state: PrisonBreakStore, winner: Creature, loser: Creature) { if (loser.type === 'player') { const updateState = updateLogDirect( state, <span> You have no health left and die! <p style={{ fontSize: '20px' }}>GAME OVER</p> </span> ); return resetWorld(updateState, 'game over'); } winner.score += loser.maxHP; let updateState = updateEntity(state, winner.id, 'score', winner.score); updateState = updateEntity(updateState, loser.id, 'locationId', null); const vicHP = Math.min(winner.maxHP, winner.currentHP + Math.round(winner.maxHP * 0.1)); updateState = updateEntity(updateState, winner.id, 'currentHP', vicHP); updateState = updateLogDirect( updateState, <span> You defeated {loser.name}! </span> ); if (loser.name === 'Warden') { updateState = updateLogDirect( updateState, <span> <p> The Warden lays dying and says with his final words: <br /> You may have won your freedom from this prison, but you shall meet your end in the town beyond... <br /> With that the Warden breaths his last breath. <br /> You leap over his body and run up the flight of stairs finally escaping this hellish place </p> <p style={{ fontSize: '20px' }}> CONGRATULATIONS <br /> YOU ESCAPED PRISON !!! Score: {getPlayerScore(state)} </p> </span> ); return resetWorld(updateState, 'game over'); } return updateState; } export function use(state: PrisonBreakStore, command: string) { const commandTail = tail(command.split(' ')).join(' '); const playerItems = getPlayerItems(state); const player = getPlayer(state); const foundItem = find(playerItems, item => item.name.toLowerCase() === commandTail.trim().toLowerCase()); if (!foundItem || !player) { return updateLog( state, command, <span> You cannot use {commandTail} as it is not in your inventory. </span> ); } if (includes(equipmentTypes, foundItem.type)) { return equip(state, `equip ${commandTail}`); } if (foundItem.type !== 'consumable') { return updateLog( state, command, <span> You do not know how to use {foundItem.name} </span> ); } let updateState = updateEntity(state, player.id, 'currentHP', player.maxHP); updateState = updateEntity(updateState, player.id, 'itemIds', player.itemIds.filter(itemId => itemId !== foundItem.id)); return updateLog( updateState, command, <span> You have used {foundItem.name} </span> ); }
app/javascript/mastodon/features/ui/components/onboarding_modal.js
imomix/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Permalink from '../../../components/permalink'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import ComposeForm from '../../compose/components/compose_form'; import Search from '../../compose/components/search'; import NavigationBar from '../../compose/components/navigation_bar'; import ColumnHeader from './column_header'; import Immutable from 'immutable'; const noop = () => { }; const messages = defineMessages({ home_title: { id: 'column.home', defaultMessage: 'Home' }, notifications_title: { id: 'column.notifications', defaultMessage: 'Notifications' }, local_title: { id: 'column.community', defaultMessage: 'Local timeline' }, federated_title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const PageOne = ({ acct, domain }) => ( <div className='onboarding-modal__page onboarding-modal__page-one'> <div style={{ flex: '0 0 auto' }}> <div className='onboarding-modal__page-one__elephant-friend' /> </div> <div> <h1><FormattedMessage id='onboarding.page_one.welcome' defaultMessage='Welcome to Mastodon!' /></h1> <p><FormattedMessage id='onboarding.page_one.federation' defaultMessage='Mastodon is a network of independent servers joining up to make one larger social network. We call these servers instances.' /></p> <p><FormattedMessage id='onboarding.page_one.handle' defaultMessage='You are on {domain}, so your full handle is {handle}' values={{ domain, handle: <strong>{acct}@{domain}</strong> }} /></p> </div> </div> ); PageOne.propTypes = { acct: PropTypes.string.isRequired, domain: PropTypes.string.isRequired, }; const PageTwo = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-two'> <div className='figure non-interactive'> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> <ComposeForm text='Awoo! #introductions' suggestions={Immutable.List()} mentionedDomains={[]} spoiler={false} onChange={noop} onSubmit={noop} onPaste={noop} onPickEmoji={noop} onChangeSpoilerText={noop} onClearSuggestions={noop} onFetchSuggestions={noop} onSuggestionSelected={noop} showSearch /> </div> <p><FormattedMessage id='onboarding.page_two.compose' defaultMessage='Write posts from the compose column. You can upload images, change privacy settings, and add content warnings with the icons below.' /></p> </div> ); PageTwo.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageThree = ({ me }) => ( <div className='onboarding-modal__page onboarding-modal__page-three'> <div className='figure non-interactive'> <Search value='' onChange={noop} onSubmit={noop} onClear={noop} onShow={noop} /> <div className='pseudo-drawer'> <NavigationBar account={me} /> </div> </div> <p><FormattedMessage id='onboarding.page_three.search' defaultMessage='Use the search bar to find people and look at hashtags, such as {illustration} and {introductions}. To look for a person who is not on this instance, use their full handle.' values={{ illustration: <Permalink to='/timelines/tag/illustration' href='/tags/illustration'>#illustration</Permalink>, introductions: <Permalink to='/timelines/tag/introductions' href='/tags/introductions'>#introductions</Permalink> }} /></p> <p><FormattedMessage id='onboarding.page_three.profile' defaultMessage='Edit your profile to change your avatar, bio, and display name. There, you will also find other preferences.' /></p> </div> ); PageThree.propTypes = { me: ImmutablePropTypes.map.isRequired, }; const PageFour = ({ domain, intl }) => ( <div className='onboarding-modal__page onboarding-modal__page-four'> <div className='onboarding-modal__page-four__columns'> <div className='row'> <div> <div className='figure non-interactive'><ColumnHeader icon='home' type={intl.formatMessage(messages.home_title)} /></div> <p><FormattedMessage id='onboarding.page_four.home' defaultMessage='The home timeline shows posts from people you follow.' /></p> </div> <div> <div className='figure non-interactive'><ColumnHeader icon='bell' type={intl.formatMessage(messages.notifications_title)} /></div> <p><FormattedMessage id='onboarding.page_four.notifications' defaultMessage='The notifications column shows when someone interacts with you.' /></p> </div> </div> <div className='row'> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='users' type={intl.formatMessage(messages.local_title)} /></div> </div> <div> <div className='figure non-interactive' style={{ marginBottom: 0 }}><ColumnHeader icon='globe' type={intl.formatMessage(messages.federated_title)} /></div> </div> </div> <p><FormattedMessage id='onboarding.page_five.public_timelines' defaultMessage='The local timeline shows public posts from everyone on {domain}. The federated timeline shows public posts from everyone who people on {domain} follow. These are the Public Timelines, a great way to discover new people.' values={{ domain }} /></p> </div> </div> ); PageFour.propTypes = { domain: PropTypes.string.isRequired, intl: PropTypes.object.isRequired, }; const PageSix = ({ admin, domain }) => { let adminSection = ''; if (admin) { adminSection = ( <p> <FormattedMessage id='onboarding.page_six.admin' defaultMessage="Your instance's admin is {admin}." values={{ admin: <Permalink href={admin.get('url')} to={`/accounts/${admin.get('id')}`}>@{admin.get('acct')}</Permalink> }} /> <br /> <FormattedMessage id='onboarding.page_six.read_guidelines' defaultMessage="Please read {domain}'s {guidelines}!" values={{ domain, guidelines: <a href='/about/more' target='_blank'><FormattedMessage id='onboarding.page_six.guidelines' defaultMessage='community guidelines' /></a> }} /> </p> ); } return ( <div className='onboarding-modal__page onboarding-modal__page-six'> <h1><FormattedMessage id='onboarding.page_six.almost_done' defaultMessage='Almost done...' /></h1> {adminSection} <p><FormattedMessage id='onboarding.page_six.github' defaultMessage='Mastodon is free open-source software. You can report bugs, request features, or contribute to the code on {github}.' values={{ github: <a href='https://github.com/tootsuite/mastodon' target='_blank' rel='noopener'>GitHub</a> }} /></p> <p><FormattedMessage id='onboarding.page_six.apps_available' defaultMessage='There are {apps} available for iOS, Android and other platforms.' values={{ apps: <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' target='_blank' rel='noopener'><FormattedMessage id='onboarding.page_six.various_app' defaultMessage='mobile apps' /></a> }} /></p> <p><em><FormattedMessage id='onboarding.page_six.appetoot' defaultMessage='Bon Appetoot!' /></em></p> </div> ); }; PageSix.propTypes = { admin: ImmutablePropTypes.map, domain: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ me: state.getIn(['accounts', state.getIn(['meta', 'me'])]), admin: state.getIn(['accounts', state.getIn(['meta', 'admin'])]), domain: state.getIn(['meta', 'domain']), }); class OnboardingModal extends React.PureComponent { static propTypes = { onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, me: ImmutablePropTypes.map.isRequired, domain: PropTypes.string.isRequired, admin: ImmutablePropTypes.map, }; state = { currentIndex: 0, }; componentWillMount() { const { me, admin, domain, intl } = this.props; this.pages = [ <PageOne acct={me.get('acct')} domain={domain} />, <PageTwo me={me} />, <PageThree me={me} />, <PageFour domain={domain} intl={intl} />, <PageSix admin={admin} domain={domain} />, ]; }; componentDidMount() { window.addEventListener('keyup', this.handleKeyUp); } componentWillUnmount() { window.addEventListener('keyup', this.handleKeyUp); } handleSkip = (e) => { e.preventDefault(); this.props.onClose(); } handleDot = (e) => { const i = Number(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.setState({ currentIndex: i }); } handlePrev = () => { this.setState(({ currentIndex }) => ({ currentIndex: Math.max(0, currentIndex - 1), })); } handleNext = () => { const { pages } = this; this.setState(({ currentIndex }) => ({ currentIndex: Math.min(currentIndex + 1, pages.length - 1), })); } handleKeyUp = ({ key }) => { switch (key) { case 'ArrowLeft': this.handlePrev(); break; case 'ArrowRight': this.handleNext(); break; } } handleClose = () => { this.props.onClose(); } render () { const { pages } = this; const { currentIndex } = this.state; const hasMore = currentIndex < pages.length - 1; const nextOrDoneBtn = hasMore ? ( <button onClick={this.handleNext} className='onboarding-modal__nav onboarding-modal__next' > <FormattedMessage id='onboarding.next' defaultMessage='Next' /> </button> ) : ( <button onClick={this.handleClose} className='onboarding-modal__nav onboarding-modal__done' > <FormattedMessage id='onboarding.done' defaultMessage='Done' /> </button> ); const styles = pages.map((data, i) => ({ key: `page-${i}`, data, style: { opacity: spring(i === currentIndex ? 1 : 0), }, })); return ( <div className='modal-root__modal onboarding-modal'> <TransitionMotion styles={styles}> {interpolatedStyles => ( <div className='onboarding-modal__pager'> {interpolatedStyles.map(({ key, data, style }, i) => { const className = classNames('onboarding-modal__page__wrapper', { 'onboarding-modal__page__wrapper--active': i === currentIndex, }); return ( <div key={key} style={style} className={className}>{data}</div> ); })} </div> )} </TransitionMotion> <div className='onboarding-modal__paginator'> <div> <button onClick={this.handleSkip} className='onboarding-modal__nav onboarding-modal__skip' > <FormattedMessage id='onboarding.skip' defaultMessage='Skip' /> </button> </div> <div className='onboarding-modal__dots'> {pages.map((_, i) => { const className = classNames('onboarding-modal__dot', { active: i === currentIndex, }); return ( <div key={`dot-${i}`} role='button' tabIndex='0' data-index={i} onClick={this.handleDot} className={className} /> ); })} </div> <div> {nextOrDoneBtn} </div> </div> </div> ); } } export default connect(mapStateToProps)(injectIntl(OnboardingModal));
App/Containers/HomeContainer.js
bretth18/PresidioWallet
'use strict'; /* container binds action creators and inject state/dispatchers as props */ import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Home from '../Components/Home'; import * as HomeActions from '../Actions/homeActions'; class HomeContainer extends Component { render() { return ( <Home {...this.props} /> ); } } function mapStateToProps(state) { return { currentAddress: state.home.currentAddress, currentBTCPrice: state.home.currentBTCPrice, walletObject: state.home.walletObject, currentBalance: state.home.currentBalance, }; } function mapDispatchToProps(dispatch) { return bindActionCreators(HomeActions,dispatch); } export default connect(mapStateToProps,mapDispatchToProps)(HomeContainer);
views/blocks/Button/Button.js
AlSoEdit/team5
import React from 'react'; import './Button.css'; import b from 'b_'; const button = b.lock('button'); export default class Button extends React.Component { render() { const {disabled, text, type, inProgress, onClick} = this.props; return ( <button type={type} disabled={disabled} className={button({inProgress})} onClick={onClick} > {text} </button> ); } }
src/app/routes.js
paulawasylow/e-commerce-react-app
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import HomeContainer from './containers/HomeContainer'; import CategoryContainer from './containers/CategoryContainer'; import NotExist from './components/NotExist'; export default ( <Route path="/" component={App}> <IndexRoute component={HomeContainer} /> <Route path="/:category" component={CategoryContainer} /> <Route path="*" component={NotExist} /> </Route> )
docs/src/app/components/pages/components/RaisedButton/Page.js
skarnecki/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import raisedButtonReadmeText from './README'; import raisedButtonExampleSimpleCode from '!raw!./ExampleSimple'; import RaisedButtonExampleSimple from './ExampleSimple'; import raisedButtonExampleComplexCode from '!raw!./ExampleComplex'; import RaisedButtonExampleComplex from './ExampleComplex'; import raisedButtonExampleIconCode from '!raw!./ExampleIcon'; import RaisedButtonExampleIcon from './ExampleIcon'; import raisedButtonCode from '!raw!material-ui/lib/RaisedButton/RaisedButton'; const descriptions = { simple: '`RaisedButton` with default color, `primary`, `secondary` and and `disabled` props applied.', complex: 'The first example uses an `input` as a child component, ' + 'the next has next has an [SVG Icon](/#/components/svg-icon), with the label positioned after. ' + 'The final example uses a [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.', icon: 'Examples of Raised Buttons using an icon without a label. The first example uses an' + ' [SVG Icon](/#/components/svg-icon), and has the default color. The second example shows' + ' how the icon and background color can be changed. The final example uses a' + ' [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.', }; const RaisedButtonPage = () => ( <div> <Title render={(previousTitle) => `Raised Button - ${previousTitle}`} /> <MarkdownElement text={raisedButtonReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={raisedButtonExampleSimpleCode} > <RaisedButtonExampleSimple /> </CodeExample> <CodeExample title="Complex examples" description={descriptions.complex} code={raisedButtonExampleComplexCode} > <RaisedButtonExampleComplex /> </CodeExample> <CodeExample title="Icon examples" description={descriptions.icon} code={raisedButtonExampleIconCode} > <RaisedButtonExampleIcon /> </CodeExample> <PropTypeDescription code={raisedButtonCode} /> </div> ); export default RaisedButtonPage;
src/routes/register/Register.js
joaquingatica/git-demo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Register.css'; class Register extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Register);
assets/javascripts/kitten/components/layer/overlay/stories.js
KissKissBankBank/kitten
import React from 'react' import { Overlay } from './index' import { Button } from 'kitten' import { DocsPage } from 'storybook/docs-page' const TOGGLE_EVENT = 'event:toggle' const CLOSE_EVENT = 'event:close' const OPEN_EVENT = 'event:open' const handleToggleClick = () => window.dispatchEvent(new Event(TOGGLE_EVENT)) const handleCloseClick = () => window.dispatchEvent(new Event(CLOSE_EVENT)) const handleOpenClick = () => window.dispatchEvent(new Event(OPEN_EVENT)) export default { title: 'Layer/Overlay', component: Overlay, parameters: { docs: { page: () => <DocsPage filepath={__filename} importString="Overlay" />, }, }, decorators: [story => <div className="story-Container">{story()}</div>], args: { zIndex: -1, isActive: false, toggleEvent: TOGGLE_EVENT, closeEvent: CLOSE_EVENT, openEvent: OPEN_EVENT, position: 'absolute', }, } export const Default = args => ( <> <Overlay {...args} /> <Button onClick={handleToggleClick}>Toggle Overlay</Button> <br /> <Button onClick={handleCloseClick}>Close Overlay</Button> <br /> <Button onClick={handleOpenClick}>Open Overlay</Button> </> )
src/applications/static-pages/health-care-manage-benefits/get-medical-records-page/components/UnauthContent/index.unit.spec.js
department-of-veterans-affairs/vets-website
// Dependencies. import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; // Relative imports. import UnauthContent from '.'; describe('Get Medical Records Page <UnauthContent>', () => { it('renders what we expect', () => { const wrapper = shallow(<UnauthContent />); const text = wrapper.text(); expect(text).to.include('On this page:'); expect(text).to.include('VA Blue Button'); expect(text).to.include( 'What is VA Blue Button, and how can it help me manage my health care?', ); expect(text).to.include( 'Am I eligible to use all the features of VA Blue Button?', ); expect(text).to.include( 'Once I’m signed in, how do I access my medical records?', ); expect(text).to.include( 'Will my personal health information be protected?', ); expect(text).to.include('What if I have more questions?'); expect(text).to.include( 'What’s VHIE, and how can it help me manage my health?', ); expect(text).to.include('How do I opt out?'); expect(text).to.include('If I opt out, how can I opt back in?'); expect(text).to.include('Can I check my sharing preference status?'); wrapper.unmount(); }); });
src/modules/DesignerShow/index.js
2941972057/flower-react
/** * Created by dllo on 17/8/23. */ import React from 'react' import ReactDOM from 'react-dom' import DesignerShow from './DesignerShow' ReactDOM.render( <DesignerShow />, document.getElementById('app') )
node_modules/react-bootstrap/es/ModalHeader.js
geng890518/editor-ui
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 PropTypes from 'prop-types'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; // TODO: `aria-label` should be `closeLabel`. var propTypes = { /** * The 'aria-label' attribute provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ 'aria-label': PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: PropTypes.func }; var defaultProps = { 'aria-label': 'Close', closeButton: false }; var contextTypes = { $bs_modal: PropTypes.shape({ onHide: PropTypes.func }) }; var ModalHeader = function (_React$Component) { _inherits(ModalHeader, _React$Component); function ModalHeader() { _classCallCheck(this, ModalHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalHeader.prototype.render = function render() { var _props = this.props, label = _props['aria-label'], closeButton = _props.closeButton, onHide = _props.onHide, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'children']); var modal = this.context.$bs_modal; var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement( 'div', _extends({}, elementProps, { className: classNames(className, classes) }), closeButton && React.createElement( 'button', { type: 'button', className: 'close', 'aria-label': label, onClick: createChainedFunction(modal && modal.onHide, onHide) }, React.createElement( 'span', { 'aria-hidden': 'true' }, '\xD7' ) ), children ); }; return ModalHeader; }(React.Component); ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; ModalHeader.contextTypes = contextTypes; export default bsClass('modal-header', ModalHeader);
Example/__tests__/index.ios.js
billoosijok/react-native-interactive-card
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 /> ); });
src/Parser/Hunter/Shared/Modules/Items/TheShadowHuntersVoodooMask.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import ItemHealingDone from 'Main/ItemHealingDone'; /** * The Shadow Hunter's Voodoo Mask * Heal for 20% of your maximum health when you activate Feign Death then heal for an additional 5% of your maximum health every sec afterwards for 10 sec while still Feigning Death. UPDATE PLEASE */ class TheShadowHuntersVoodooMask extends Analyzer { static dependencies = { combatants: Combatants, }; healing = 0; on_initialized() { this.active = this.combatants.selected.hasHead(ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.THE_SHADOW_HUNTERS_VOODOO_MASK_HEAL.id) { this.healing += event.amount; } } item() { return { item: ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK, result: <ItemHealingDone amount={this.healing} />, }; } } export default TheShadowHuntersVoodooMask;
admin/client/App/screens/Item/index.js
giovanniRodighiero/cms
/** * Item View * * This is the item view, it is rendered when users visit a page of a specific * item. This mainly renders the form to edit the item content in. */ import React from 'react'; import { Center, Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { listsByKey } from '../../../utils/lists'; import CreateForm from '../../shared/CreateForm'; import Alert from '../../elemental/Alert'; import EditForm from './components/EditForm'; import EditFormHeader from './components/EditFormHeader'; import RelatedItemsList from './components/RelatedItemsList/RelatedItemsList'; // import FlashMessages from '../../shared/FlashMessages'; import { selectItem, loadItemData, } from './actions'; import { selectList, } from '../List/actions'; var ItemView = React.createClass({ displayName: 'ItemView', contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { createIsOpen: false, }; }, componentDidMount () { // When we directly navigate to an item without coming from another client // side routed page before, we need to select the list before initializing the item // We also need to update when the list id has changed if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) { this.props.dispatch(selectList(this.props.params.listId)); } this.initializeItem(this.props.params.itemId); }, componentWillReceiveProps (nextProps) { // We've opened a new item from the client side routing, so initialize // again with the new item id if (nextProps.params.itemId !== this.props.params.itemId) { this.props.dispatch(selectList(nextProps.params.listId)); this.initializeItem(nextProps.params.itemId); } }, // Initialize an item initializeItem (itemId) { this.props.dispatch(selectItem(itemId)); this.props.dispatch(loadItemData()); }, // Called when a new item is created onCreate (item) { // Hide the create form this.toggleCreateModal(false); // Redirect to newly created item path const list = this.props.currentList; this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`); }, // Open and close the create new item modal toggleCreateModal (visible) { this.setState({ createIsOpen: visible, }); }, // Render this items relationships renderRelationships () { const { relationships } = this.props.currentList; const keys = Object.keys(relationships); if (!keys.length) return; return ( <div className="Relationships"> <Container> <h2>Relationships</h2> {keys.map(key => { const relationship = relationships[key]; const refList = listsByKey[relationship.ref]; const { currentList, params, relationshipData, drag } = this.props; return ( <RelatedItemsList key={relationship.path} list={currentList} refList={refList} relatedItemId={params.itemId} relationship={relationship} items={relationshipData[relationship.path]} dragNewSortOrder={drag.newSortOrder} dispatch={this.props.dispatch} /> ); })} </Container> </div> ); }, // Handle errors handleError (error) { const detail = error.detail; if (detail) { // Item not found if (detail.name === 'CastError' && detail.path === '_id') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> No item matching id "{this.props.routeParams.itemId}".&nbsp; <Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}> Got back to {this.props.routeParams.listId}? </Link> </Alert> </Container> ); } } if (error.message) { // Server down + possibly other errors if (error.message === 'Internal XMLHttpRequest Error') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> We encountered some network problems, please refresh. </Alert> </Container> ); } } return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> An unknown error has ocurred, please refresh. </Alert> </Container> ); }, render () { // If we don't have any data yet, show the loading indicator if (!this.props.ready) { return ( <Center height="50vh" data-screen-id="item"> <Spinner /> </Center> ); } // When we have the data, render the item view with it return ( <div data-screen-id="item"> {(this.props.error) ? this.handleError(this.props.error) : ( <div> <Container> <EditFormHeader list={this.props.currentList} data={this.props.data} toggleCreate={this.toggleCreateModal} /> <CreateForm list={this.props.currentList} isOpen={this.state.createIsOpen} onCancel={() => this.toggleCreateModal(false)} onCreate={(item) => this.onCreate(item)} /> <EditForm list={this.props.currentList} data={this.props.data} dispatch={this.props.dispatch} router={this.context.router} /> </Container> {this.renderRelationships()} </div> )} </div> ); }, }); module.exports = connect((state) => ({ data: state.item.data, loading: state.item.loading, ready: state.item.ready, error: state.item.error, currentList: state.lists.currentList, relationshipData: state.item.relationshipData, drag: state.item.drag, }))(ItemView);
react/features/settings/components/web/audio/SpeakerEntry.js
jitsi/jitsi-meet
// @flow import React, { Component } from 'react'; import logger from '../../../logger'; import AudioSettingsEntry from './AudioSettingsEntry'; import TestButton from './TestButton'; const TEST_SOUND_PATH = 'sounds/ring.wav'; /** * The type of the React {@code Component} props of {@link SpeakerEntry}. */ type Props = { /** * The text label for the entry. */ children: React$Node, /** * Flag controlling the selection state of the entry. */ isSelected: boolean, /** * Flag controlling the selection state of the entry. */ index: number, /** * Flag controlling the selection state of the entry. */ length: number, /** * The deviceId of the speaker. */ deviceId: string, /** * Click handler for the component. */ onClick: Function, listHeaderId: string }; /** * Implements a React {@link Component} which displays an audio * output settings entry. The user can click and play a test sound. * * @augments Component */ export default class SpeakerEntry extends Component<Props> { /** * A React ref to the HTML element containing the {@code audio} instance. */ audioRef: Object; /** * Initializes a new {@code SpeakerEntry} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props: Props) { super(props); this.audioRef = React.createRef(); this._onTestButtonClick = this._onTestButtonClick.bind(this); this._onClick = this._onClick.bind(this); this._onKeyPress = this._onKeyPress.bind(this); } _onClick: () => void; /** * Click handler for the entry. * * @returns {void} */ _onClick() { this.props.onClick(this.props.deviceId); } _onKeyPress: () => void; /** * Key pressed handler for the entry. * * @param {Object} e - The event. * @private * * @returns {void} */ _onKeyPress(e) { if (e.key === ' ') { e.preventDefault(); this.props.onClick(this.props.deviceId); } } _onTestButtonClick: Object => void; /** * Click handler for Test button. * Sets the current audio output id and plays a sound. * * @param {Object} e - The sythetic event. * @returns {void} */ async _onTestButtonClick(e) { e.stopPropagation(); try { await this.audioRef.current.setSinkId(this.props.deviceId); this.audioRef.current.play(); } catch (err) { logger.log('Could not set sink id', err); } } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { children, isSelected, index, deviceId, length, listHeaderId } = this.props; const deviceTextId: string = `choose_speaker${deviceId}`; const labelledby: string = `${listHeaderId} ${deviceTextId} `; return ( <li aria-checked = { isSelected } aria-labelledby = { labelledby } aria-posinset = { index } aria-setsize = { length } className = 'audio-preview-speaker' onClick = { this._onClick } onKeyPress = { this._onKeyPress } role = 'radio' tabIndex = { 0 }> <AudioSettingsEntry isSelected = { isSelected } key = { deviceId } labelId = { deviceTextId }> {children} </AudioSettingsEntry> <TestButton onClick = { this._onTestButtonClick } onKeyPress = { this._onTestButtonClick } /> <audio preload = 'auto' ref = { this.audioRef } src = { TEST_SOUND_PATH } /> </li> ); } }
src/routes/error/index.js
kevinchau321/TReactr
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ error }) { return { title: error.name, description: error.message, component: <ErrorPage error={error} />, status: error.status || 500, }; }, };
client/src/components/billing/initial-checkout.js
RajivLinkites/Starter-Skeleton
import React, { Component } from 'react'; import CheckoutForm from './checkout-form'; class InitialCheckout extends Component { render() { return ( <CheckoutForm plan={this.props.params.plan} /> ); } } export default InitialCheckout;
src/components/Button.js
colouroscope/colouroscope
import React from 'react' import classNames from 'classnames' let Button = ({ onClick, children, className }) => ( <button className={classNames('btn', 'btn-secondary', className)} onClick={onClick}>{children}</button> ) export default Button
screens/MoresScreen/index.js
nattatorn-dev/expo-with-realworld
import React from 'react' import { ScrollView, View } from 'react-native' import PropTypes from 'prop-types' import { Colors } from 'constants' import Mores from './MoresContainer' import { Search } from '@components' const MoresScreen = ( { navigation } ) => ( <ScrollView> <Mores navigation={navigation} /> </ScrollView> ) MoresScreen.navigationOptions = ( { navigation } ) => ( { header: ( <View style={{ backgroundColor: Colors.tintColor }}> <Search navigation={navigation} navOnCancel={'mores'} /> </View> ), } ) MoresScreen.propTypes = { navigation: PropTypes.object.isRequired, } export default MoresScreen
src/layouts/index.js
colsondonohue/colsondonohue.github.io
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import Container from '../components/Container'; import Header from '../components/Header'; import Footer from '../components/Footer'; import './index.css'; const propTypes = { children: PropTypes.func }; const TemplateWrapper = ({ children }) => <div> <Helmet title="Colson Donohue" meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' } ]} /> <Header /> <Container> {children()} </Container> <Footer /> </div>; TemplateWrapper.propTypes = propTypes; export default TemplateWrapper;
src/components/header/index.js
jackblackCH/zululo
import React from 'react'; import './Header.css' export default () => <header className="c-header"><a href="/"><img alt="" className="c-header__logo" src='/assets/logo.png' /></a></header>
app/packs/src/components/computed_props/Highlight.js
ComPlat/chemotion_ELN
import React from 'react'; import { ScaleUtils, AbstractSeries } from 'react-vis'; function cropDimension(loc, startLoc, minLoc, maxLoc) { if (loc < startLoc) { return { start: Math.max(loc, minLoc), stop: startLoc }; } return { stop: Math.min(loc, maxLoc), start: startLoc }; } export default class Highlight extends AbstractSeries { constructor(props) { super(props); this.state = { drawing: false, drawArea: { top: 0, right: 0, bottom: 0, left: 0 }, x_start: 0, y_start: 0, xMode: false, yMode: false, xyMode: false }; this.stopDrawing = this.stopDrawing.bind(this); this.onParentMouseDown = this.onParentMouseDown.bind(this); this.getMousePosition = this.getMousePosition.bind(this); } componentDidMount() { document.addEventListener('mouseup', this.stopDrawing); } componentWillUnmount() { document.removeEventListener('mouseup', this.stopDrawing); } getDrawArea(loc) { const { innerWidth, innerHeight } = this.props; const { drawArea, xStart, yStart, xMode, yMode, xyMode } = this.state; const { x, y } = loc; let out = drawArea; if (xMode || xyMode) { const { start, stop } = cropDimension(x, xStart, 0, innerWidth); out = { ...out, left: start, right: stop }; } if (yMode || xyMode) { const { start, stop } = cropDimension(y, yStart, 0, innerHeight); out = { ...out, top: innerHeight - start, bottom: innerHeight - stop }; } return out; } onParentMouseDown(e) { const { innerHeight, innerWidth, onBrushStart } = this.props; const { x, y } = this.getMousePosition(e); const yRect = innerHeight - y; if (x < 0 && y >= 0) { this.setState({ yMode: true, drawing: true, drawArea: { top: yRect, right: innerWidth, bottom: yRect, left: 0 }, yStart: y }); } else if (x >= 0 && y < 0) { this.setState({ xMode: true, drawing: true, drawArea: { top: innerHeight, right: x, bottom: 0, left: x }, xStart: x }); } else if (x >= 0 && y >= 0) { this.setState({ xyMode: true, drawing: true, drawArea: { top: yRect, right: x, bottom: yRect, left: x }, xStart: x, yStart: y }); } if (onBrushStart) { onBrushStart(e); } } // onParentTouchStart(e) { // e.preventDefault(); // this.onParentMouseDown(e); // } stopDrawing() { this.setState({ xMode: false, yMode: false, xyMode: false }); if (!this.state.drawing) { return; } const { onBrushEnd } = this.props; const { drawArea } = this.state; const xScale = ScaleUtils.getAttributeScale(this.props, 'x'); const yScale = ScaleUtils.getAttributeScale(this.props, 'y'); // Clear the draw area this.setState({ drawing: false, drawArea: { top: 0, right: 0, bottom: 0, left: 0 }, xStart: 0, yStart: 0 }); if (Math.abs(drawArea.right - drawArea.left) < 5) { onBrushEnd(null); return; } const domainArea = { bottom: yScale.invert(drawArea.top), right: xScale.invert(drawArea.right), top: yScale.invert(drawArea.bottom), left: xScale.invert(drawArea.left) }; if (onBrushEnd) { onBrushEnd(domainArea); } } getMousePosition(e) { const { marginLeft, marginTop, innerHeight } = this.props; const locX = e.nativeEvent.offsetX - marginLeft; const locY = (innerHeight + marginTop) - e.nativeEvent.offsetY; return { x: locX, y: locY }; } onParentMouseMove(e) { const { drawing } = this.state; if (drawing) { const pos = this.getMousePosition(e); const newDrawArea = this.getDrawArea(pos); this.setState({ drawArea: newDrawArea }); } } render() { const { marginLeft, marginTop, innerWidth, innerHeight, color, opacity } = this.props; const { drawArea: { left, right, top, bottom } } = this.state; return ( <g transform={`translate(${marginLeft}, ${marginTop})`} className="highlight-container" > <rect opacity="0" x={0} y={0} width={innerWidth} height={innerHeight} /> <rect pointerEvents="none" opacity={opacity} fill={color} x={left} y={bottom} width={right - left} height={top - bottom} /> </g> ); } } const defaultProps = { allow: 'x', color: 'rgb(77, 182, 172)', opacity: 0.3 }; Highlight.defaultProps = { ...AbstractSeries, ...defaultProps }; Highlight.displayName = 'ComputedPropsGraphHighlight';
blueprints/smart/files/__root__/containers/__name__.js
availabs/kauffman-atlas
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' type Props = { } export class <%= pascalEntityName %> extends React.Component { props: Props; render() { return ( <div></div> ) } } const mapStateToProps = (state) => { return {} } const mapDispatchToProps = (dispatch) => { return {} } export default connect( mapStateToProps, mapDispatchToProps )(<%= pascalEntityName %>)
client/components/position-table/PositionTableContainer.js
kanehara/yostock
import React from 'react' import services from '../../services' import { PositionTable } from './PositionTable' export class PositionTableContainer extends React.Component { constructor(props) { super(props) this.state = { positions: services.PositionService.getPositions() } } render() { return ( <PositionTable positions={this.state.positions}/> ) } }
src/svg-icons/toggle/star.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStar = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ToggleStar = pure(ToggleStar); ToggleStar.displayName = 'ToggleStar'; ToggleStar.muiName = 'SvgIcon'; export default ToggleStar;
src/components/chart.js
StephanYu/modern_redux_weather_forecast
import _ from 'lodash'; import React from 'react'; import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines'; function average(data) { return _.round(_.sum(data)/data.length); } export default (props) => { return( <div> <Sparklines height={120} width={180} data={props.data}> <SparklinesLine color={props.color} /> <SparklinesReferenceLine type="avg" /> </Sparklines> <div>{average(props.data)} {props.units}</div> </div> ); }
app/components/news/category.js
sonic182/gnosisapp
import React, { Component } from 'react'; import { View, Text, StyleSheet, Platform, } from 'react-native'; import utils from '../../utils/utils'; const Touchable = utils.Touchable; export default class Category extends Component { render () { const categoryStyle = [styles.category] const categoryTextStyle = [styles.categoryText] const categoryTextSelectedStyle = [styles.categoryTextSelected] const categorySelectedStyle = [styles.categorySelected] return ( <Touchable accessibilityComponentType="button" onPress={this.props.onPress} style={styles.category}> <View style={this.props.selected ? categorySelectedStyle : categoryStyle}> <Text style={this.props.selected ? categoryTextSelectedStyle: categoryTextStyle}>{this.props.name}</Text> </View> </Touchable> ) } } const styles = StyleSheet.create({ category: { backgroundColor: 'blue', height: 40, paddingVertical: 10, paddingHorizontal: 30, }, category: Platform.select({ ios: {}, android: { elevation: 4, backgroundColor: '#ffffff', // borderRadius: 2, paddingHorizontal: 7 }, }), categorySelected: Platform.select({ ios: {}, android: { elevation: 4, backgroundColor: '#ffffff', backgroundColor: '#444', // color: '#ffffff', // borderRadius: 2, paddingHorizontal: 7 }, }), categoryText: Platform.select({ ios: { color: '#444', textAlign: 'center', padding: 8, fontSize: 18, }, android: { textAlign: 'center', color: '#444', padding: 8, fontWeight: '500', }, }), categoryTextSelected: Platform.select({ ios: { color: '#444', textAlign: 'center', padding: 8, fontSize: 18, }, android: { textAlign: 'center', color: 'white', padding: 8, fontWeight: '500', }, }), })
packages/material-ui-icons/src/AssistantPhoto.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z" /></g> , 'AssistantPhoto');
src/components/app.js
AdevaS/weather_redux
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
src/routes/post/index.js
Grusteam/spark-in-me
import React from 'react'; import Layout from '../../components/Layout'; import Post from '../../components/Post'; import request from '../../core/request'; import {sortMetatags} from '../../core/sortMetatags'; export default { path: '/post/:alias', async action(args) { const responseGlobal = await request('getBlogObjects'), responsePosts = await request('getArticleByAlias', {'articleAlias': args.params.alias}, args.params.alias), responseAuthors = await request('getAuthorByAlias', {'authorAlias': 'all-authors', 'getFullArticles': 0}), responseSimilar = await request('getSimilarArticlesByArticleAlias', {'articleAlias': args.params.alias}); if (!responseGlobal || !responsePosts || !responsePosts.response.data || !responseAuthors || !responseSimilar) { return { redirect: '/error' }; } const glogalData = responseGlobal.response.data, curPage = glogalData.globals.pages.home, postContent = responsePosts.response.data[0], pageData = { title: postContent.title, subtitle: postContent.subtitle, bg: postContent.main_picture, footer: { footerText: glogalData.globals.footer_text, soc: glogalData.social }, nav: { menu: glogalData.globals.nav_items, logo: glogalData.globals.site_title }, authors: postContent.author_info, dateP: postContent.published, back: true, post: true, leftNav: { soc: glogalData.social, authors: responseAuthors.response.data, similar: true, similarList: responseSimilar.response.data }, ldjson: JSON.stringify(postContent.ld_json), breadcrumbs: JSON.stringify(postContent.bread_crumbs) }, postContentInfo = { content: postContent.content, tags: postContent.article_tags, alias: postContent.slug, disqusUrl: postContent.disqus_article_url }; return { meta: sortMetatags(postContent.article_meta), title: postContent.title, component: <Layout data={pageData} ><Post content={postContentInfo}/></Layout>, }; }, };
platform/viewer/src/connectedComponents/ViewerLocalFileData.js
OHIF/Viewers
import React, { Component } from 'react'; import { metadata, utils } from '@ohif/core'; import ConnectedViewer from './ConnectedViewer.js'; import PropTypes from 'prop-types'; import { extensionManager } from './../App.js'; import Dropzone from 'react-dropzone'; import filesToStudies from '../lib/filesToStudies'; import './ViewerLocalFileData.css'; import { withTranslation } from 'react-i18next'; const { OHIFStudyMetadata } = metadata; const { studyMetadataManager } = utils; const dropZoneLinkDialog = (onDrop, i18n, dir) => { return ( <Dropzone onDrop={onDrop} noDrag> {({ getRootProps, getInputProps }) => ( <span {...getRootProps()} className="link-dialog"> {dir ? ( <span> {i18n('Load folders')} <input {...getInputProps()} webkitdirectory="true" mozdirectory="true" /> </span> ) : ( <span> {i18n('Load files')} <input {...getInputProps()} /> </span> )} </span> )} </Dropzone> ); }; const linksDialogMessage = (onDrop, i18n) => { return ( <> {i18n('Or click to ')} {dropZoneLinkDialog(onDrop, i18n)} {i18n(' or ')} {dropZoneLinkDialog(onDrop, i18n, true)} {i18n(' from dialog')} </> ); }; class ViewerLocalFileData extends Component { static propTypes = { studies: PropTypes.array, }; state = { studies: null, loading: false, error: null, }; updateStudies = studies => { // Render the viewer when the data is ready studyMetadataManager.purge(); // Map studies to new format, update metadata manager? const updatedStudies = studies.map(study => { const studyMetadata = new OHIFStudyMetadata( study, study.StudyInstanceUID ); const sopClassHandlerModules = extensionManager.modules['sopClassHandlerModule']; study.displaySets = study.displaySets || studyMetadata.createDisplaySets(sopClassHandlerModules); studyMetadata.forEachDisplaySet(displayset => { displayset.localFile = true; }); studyMetadataManager.add(studyMetadata); return study; }); this.setState({ studies: updatedStudies, }); }; render() { const onDrop = async acceptedFiles => { this.setState({ loading: true }); const studies = await filesToStudies(acceptedFiles); const updatedStudies = this.updateStudies(studies); if (!updatedStudies) { return; } this.setState({ studies: updatedStudies, loading: false }); }; if (this.state.error) { return <div>Error: {JSON.stringify(this.state.error)}</div>; } return ( <Dropzone onDrop={onDrop} noClick> {({ getRootProps, getInputProps }) => ( <div {...getRootProps()} style={{ width: '100%', height: '100%' }}> {this.state.studies ? ( <ConnectedViewer studies={this.state.studies} studyInstanceUIDs={ this.state.studies && this.state.studies.map(a => a.StudyInstanceUID) } /> ) : ( <div className={'drag-drop-instructions'}> <div className={'drag-drop-contents'}> {this.state.loading ? ( <h3>{this.props.t('Loading...')}</h3> ) : ( <> <h3> {this.props.t( 'Drag and Drop DICOM files here to load them in the Viewer' )} </h3> <h4>{linksDialogMessage(onDrop, this.props.t)}</h4> </> )} </div> </div> )} </div> )} </Dropzone> ); } } export default withTranslation('Common')(ViewerLocalFileData);
app/javascript/mastodon/features/favourited_statuses/index.js
pinfort/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites'; import Column from '../ui/components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import StatusList from '../../components/status_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { debounce } from 'lodash'; const messages = defineMessages({ heading: { id: 'column.favourites', defaultMessage: 'Favourites' }, }); const mapStateToProps = state => ({ statusIds: state.getIn(['status_lists', 'favourites', 'items']), isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true), hasMore: !!state.getIn(['status_lists', 'favourites', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Favourites extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, isLoading: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFavouritedStatuses()); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('FAVOURITES', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = debounce(() => { this.props.dispatch(expandFavouritedStatuses()); }, 300, { leading: true }) render () { const { intl, shouldUpdateScroll, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite toots yet. When you favourite one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}> <ColumnHeader icon='star' title={intl.formatMessage(messages.heading)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusList trackScroll={!pinned} statusIds={statusIds} scrollKey={`favourited_statuses-${columnId}`} hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} /> </Column> ); } }
packages/icons/src/md/action/Delete.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdDelete(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M12 38c0 2.21 1.79 4 4 4h16c2.21 0 4-1.79 4-4V14H12v24zM38 8h-7l-2-2H19l-2 2h-7v4h28V8z" /> </IconBase> ); } export default MdDelete;
src/components/ProfileInfo/ProfilePhone.js
dialogs/dialog-native-components
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import type { Phone } from '@dlghq/dialog-types'; import React from 'react'; import { Text } from 'react-native'; import PhoneNumber from 'awesome-phonenumber'; type Props = { phone: Phone }; function formatPhone(phone: string) { try { return PhoneNumber('+' + phone).getNumber('international'); } catch (e) { console.error(e); return phone; } } function ProfilePhone(props: Props) { return ( <Text> {formatPhone(props.phone.number)} </Text> ); } export default ProfilePhone;
src/Heading.js
itsolutions-dev/react-styled-ui
// @flow import React from 'react'; import Heading1 from './Heading1'; import Heading2 from './Heading2'; import Heading3 from './Heading3'; import Heading4 from './Heading4'; import Heading5 from './Heading5'; import Heading6 from './Heading6'; const headings = [ Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, ]; type HeadingProps = { size: 1 | 2 | 3 | 4 | 5 | 6, }; const Heading = ({ size = 1, ...others }: HeadingProps) => { const Component = headings[size - 1]; return <Component {...others} />; }; export default Heading;
src/main/react/src/main.js
mbrossard/cryptonit-cloud
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' const browserHistory = useRouterHistory(createBrowserHistory)({ basename: '' }) const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) let render = (routerKey = null) => { const routes = require('./routes/index').default(store) ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, document.getElementById('root') ) } render();
src/components/video_detail.js
theoryNine/react-video-browser
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
shared/components/StoryItem.js
AndrewGibson27/react-fetch-boilerplate
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; const StoryItem = ({ path, data: { _id, headline } }) => ( <li> <p>{headline}</p> <NavLink to={`${path}/${_id}`}>Details</NavLink> </li> ); export default StoryItem;
docs/app/Examples/collections/Form/Shorthand/FormExampleFieldLabelElement.js
koenvg/Semantic-UI-React
import React from 'react' import { Checkbox, Form } from 'semantic-ui-react' const FormExampleFieldLabelElement = () => ( <Form> <Form.Field control={Checkbox} label={{ children: 'I agree to the Terms and Conditions' }} /> </Form> ) export default FormExampleFieldLabelElement
src/index.js
dbachrach/react-imageloader
import React from 'react'; const {PropTypes} = React; const {span} = React.DOM; const Status = { PENDING: 'pending', LOADING: 'loading', LOADED: 'loaded', FAILED: 'failed', }; export default class ImageLoader extends React.Component { static propTypes = { wrapper: PropTypes.func, className: PropTypes.string, preloader: PropTypes.func, }; static defaultProps = { wrapper: span, }; constructor(props) { super(props); this.state = {status: props.src ? Status.LOADING : Status.PENDING}; } componentDidMount() { if (this.state.status === Status.LOADING) { this.createLoader(); } } componentWillReceiveProps(nextProps) { if (this.props.src !== nextProps.src) { this.setState({ status: nextProps.src ? Status.LOADING : Status.PENDING, }); } } componentDidUpdate() { if (this.state.status === Status.LOADING && !this.img) { this.createLoader(); } } componentWillUnmount() { this.destroyLoader(); } getClassName() { let className = `imageloader ${this.state.status}`; if (this.props.className) className = `${className} ${this.props.className}`; return className; } createLoader() { this.destroyLoader(); // We can only have one loader at a time. this.img = new Image(); this.img.onload = ::this.handleLoad; this.img.onerror = ::this.handleError; this.img.src = this.props.src; } destroyLoader() { if (this.img) { this.img.onload = null; this.img.onerror = null; this.img = null; } } handleLoad(event) { this.destroyLoader(); this.setState({status: Status.LOADED}); if (this.props.onLoad) this.props.onLoad(event); } handleError(error) { this.destroyLoader(); this.setState({status: Status.FAILED}); if (this.props.onError) this.props.onError(error); } renderImg() { // Reduce props to just those not used by ImageLoader. // The assumption is that any other props are meant for the loaded image. const blacklist = Object.keys(ImageLoader.propTypes).concat('children'); let props = {}; for (let k in this.props) { if (!this.props.hasOwnProperty(k)) continue; if (blacklist.indexOf(k) >= 0) continue; props[k] = this.props[k]; } return <img {...props} />; } render() { let wrapperArgs = [{className: this.getClassName()}]; switch (this.state.status) { case Status.LOADED: wrapperArgs.push(this.renderImg()); break; case Status.FAILED: if (this.props.children) wrapperArgs.push(this.props.children); break; default: if (this.props.preloader) wrapperArgs.push(this.props.preloader()); break; } return this.props.wrapper(...wrapperArgs); } }
src/containers/PlanetsPage.js
tsahnar/swapi_proj
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import WithDataHOC from '../HOC/WithDataHOC' import List from '../components/common/List' import Planet from '../components/Planet' const PlanetsPage = ({ data: planetsData }) => { return ( <div> <h4 className="page-title text-center"> Star Wars Planets: </h4> <List list={ planetsData.results } render={ planet => <Planet key={planet.url} item={ planet } /> } /> </div> ) } PlanetsPage.propTypes = { data: PropTypes.object.isRequired, }; export default WithDataHOC('https://swapi.co/api/planets/')(PlanetsPage)
javascript/AddOn/Message.js
AppStateESS/stories
import React from 'react' import PropTypes from 'prop-types' const Message = (props) => { let icon = '' switch (props.type) { case 'danger': icon = 'fas fa-exclamation-triangle' break case 'success': icon = 'far fa-thumbs-up' break case 'info': icon = 'fas fa-info-circle' break case 'warning': icon = 'far fa-hand-paper' break } let messageType = 'alert alert-dismissible alert-' + props.type let closeButton if (props.onClose !== undefined) { closeButton = ( <button type="button" onClick={props.onClose} className="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> ) } return ( <div className={messageType} role="alert"> {closeButton} <i className={icon}></i>&nbsp; {props.children} </div> ) } Message.propTypes = { type: PropTypes.string, children: PropTypes.oneOfType([PropTypes.string, PropTypes.element,]), onClose: PropTypes.func, } Message.defaultProps = { type: 'info' } export default Message
code/workspaces/web-app/src/components/app/Segment.js
NERC-CEH/datalab
import React from 'react'; import { withStyles } from '@material-ui/core/styles'; const styles = theme => ({ segment: { padding: theme.spacing(1), }, }); const Segment = ({ classes, children }) => ( <div className={classes.segment}> {children} </div> ); export default withStyles(styles)(Segment);
src/svg-icons/notification/network-check.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationNetworkCheck = (props) => ( <SvgIcon {...props}> <path d="M15.9 5c-.17 0-.32.09-.41.23l-.07.15-5.18 11.65c-.16.29-.26.61-.26.96 0 1.11.9 2.01 2.01 2.01.96 0 1.77-.68 1.96-1.59l.01-.03L16.4 5.5c0-.28-.22-.5-.5-.5zM1 9l2 2c2.88-2.88 6.79-4.08 10.53-3.62l1.19-2.68C9.89 3.84 4.74 5.27 1 9zm20 2l2-2c-1.64-1.64-3.55-2.82-5.59-3.57l-.53 2.82c1.5.62 2.9 1.53 4.12 2.75zm-4 4l2-2c-.8-.8-1.7-1.42-2.66-1.89l-.55 2.92c.42.27.83.59 1.21.97zM5 13l2 2c1.13-1.13 2.56-1.79 4.03-2l1.28-2.88c-2.63-.08-5.3.87-7.31 2.88z"/> </SvgIcon> ); NotificationNetworkCheck = pure(NotificationNetworkCheck); NotificationNetworkCheck.displayName = 'NotificationNetworkCheck'; export default NotificationNetworkCheck;
src/viewElements/shared/radioSelection/RadioBlock.js
yasavbrain/yasav
import React from 'react'; import { ListItem, Text } from 'native-base'; import Style from 'yasav/src/styles/Shared' export class RadioBlock extends React.Component { render() { if(this.props.selected){ return ( <ListItem style={Style.radioBlockSelected} onPress={this.props.onPress}> <Text style={Style.radioBlockText}>{this.props.title}</Text> </ListItem> ) }else{ return ( <ListItem style={Style.radioBlockUnselected} onPress={this.props.onPress}> <Text style={Style.radioBlockText}>{this.props.title}</Text> </ListItem> ) } } }
src/DatePicker/DatePickerDialog.js
rscnt/material-ui
import React from 'react'; import EventListener from 'react-event-listener'; import keycode from 'keycode'; import Calendar from './Calendar'; import Dialog from '../Dialog'; import DatePickerInline from './DatePickerInline'; import FlatButton from '../FlatButton'; import {dateTimeFormat} from './dateUtils'; class DatePickerDialog extends React.Component { static propTypes = { DateTimeFormat: React.PropTypes.func, autoOk: React.PropTypes.bool, cancelLabel: React.PropTypes.node, container: React.PropTypes.oneOf(['dialog', 'inline']), disableYearSelection: React.PropTypes.bool, firstDayOfWeek: React.PropTypes.number, initialDate: React.PropTypes.object, locale: React.PropTypes.string, maxDate: React.PropTypes.object, minDate: React.PropTypes.object, mode: React.PropTypes.oneOf(['portrait', 'landscape']), okLabel: React.PropTypes.node, onAccept: React.PropTypes.func, onDismiss: React.PropTypes.func, onShow: React.PropTypes.func, shouldDisableDate: React.PropTypes.func, style: React.PropTypes.object, wordings: React.PropTypes.object, }; static defaultProps = { DateTimeFormat: dateTimeFormat, container: 'dialog', locale: 'en-US', okLabel: 'OK', cancelLabel: 'Cancel', }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; state = { open: false, }; show = () => { if (this.props.onShow && !this.state.open) this.props.onShow(); this.setState({ open: true, }); }; dismiss = () => { if (this.props.onDismiss && this.state.open) this.props.onDismiss(); this.setState({ open: false, }); } handleTouchTapDay = () => { if (this.props.autoOk) { setTimeout(this.handleTouchTapOK, 300); } }; handleTouchTapCancel = () => { this.dismiss(); }; handleRequestClose = () => { this.dismiss(); }; handleTouchTapOK = () => { if (this.props.onAccept && !this.refs.calendar.isSelectedDateDisabled()) { this.props.onAccept(this.refs.calendar.getSelectedDate()); } this.dismiss(); }; handleKeyUp = (event) => { switch (keycode(event)) { case 'enter': this.handleTouchTapOK(); break; } }; render() { const { DateTimeFormat, cancelLabel, container, initialDate, firstDayOfWeek, locale, okLabel, onAccept, // eslint-disable-line no-unused-vars style, // eslint-disable-line no-unused-vars wordings, minDate, maxDate, shouldDisableDate, mode, disableYearSelection, ...other, } = this.props; const {open} = this.state; const { datePicker: { calendarTextColor, }, } = this.context.muiTheme; const styles = { root: { fontSize: 14, color: calendarTextColor, }, dialogContent: { width: mode === 'landscape' ? 480 : 320, }, dialogBodyContent: { padding: 0, }, actions: { marginRight: 8, }, }; const actions = [ <FlatButton key={0} label={wordings ? wordings.cancel : cancelLabel} primary={true} style={styles.actions} onTouchTap={this.handleTouchTapCancel} />, ]; if (!this.props.autoOk) { actions.push( <FlatButton key={1} label={wordings ? wordings.ok : okLabel} primary={true} disabled={this.refs.calendar !== undefined && this.refs.calendar.isSelectedDateDisabled()} style={styles.actions} onTouchTap={this.handleTouchTapOK} /> ); } // will change later when Popover is available. const Container = (container === 'inline' ? DatePickerInline : Dialog); return ( <Container {...other} ref="dialog" style={styles.root} contentStyle={styles.dialogContent} bodyStyle={styles.dialogBodyContent} actions={actions} repositionOnUpdate={false} open={open} onRequestClose={this.handleRequestClose} > {open && <EventListener elementName="window" onKeyUp={this.handleKeyUp} /> } {open && <Calendar DateTimeFormat={DateTimeFormat} firstDayOfWeek={firstDayOfWeek} locale={locale} ref="calendar" onDayTouchTap={this.handleTouchTapDay} initialDate={initialDate} open={true} minDate={minDate} maxDate={maxDate} shouldDisableDate={shouldDisableDate} disableYearSelection={disableYearSelection} mode={mode} /> } </Container> ); } } export default DatePickerDialog;
app/containers/Login/index.js
projectcashmere/web-server
/* * * Login * */ import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import styled from 'styled-components'; import { login } from './actions'; import { selectNextPathName } from './selectors'; import { makeSelectCurrentUser } from '../App/selectors'; import messages from './messages'; import Button from 'components/Button' export class Login extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor (props) { super(props); this.state = { email: '', password: '' } } componentWillUpdate (nextProps) { const { currentUser } = nextProps; const { nextPath } = this.props if (currentUser && window.sessionStorage.accessToken) { return nextPath ? push(nextPath) : push('/'); } } handleLogin = () => { this.props.login(this.state) } setEmail = (e) => { this.setState({ email: e.target.value }) } setPassword = (e) => { this.setState({ password: e.target.value }) } _container () { const { handleLogin, setEmail, setPassword } = this; return ( <Container> <H1> <FormattedMessage {...messages.header} /> </H1> <Input type="text" placeholder="Email" onBlur={setEmail} /> <Input type="password" placeholder="Password" onBlur={setPassword} /> <Button wide onClick={handleLogin}> <FormattedMessage {...messages.login} /> </Button> </Container> ) } render() { return ( <Wrapper> { this._container() } </Wrapper> ); } } const Wrapper = styled.div` height: calc(100vh); display: flex; justify-content: center; align-items: center; background: black; ` const Container = styled.div` display: flex; flex-direction: column; justify-content: space-between; ` const H1 = styled.h1` color: white; margin-bottom: 30px; ` const Input = styled.input` color: white; border-bottom: thin solid white; padding: 10px 3px; margin-bottom: 30px; font-size: 16px; ` const mapStateToProps = createStructuredSelector({ nextPath: selectNextPathName(), currentUser: makeSelectCurrentUser() }); const mapDispatchToProps = (dispatch) => ({ login: (info) => dispatch(login(info)) }) export default connect(mapStateToProps, mapDispatchToProps)(Login);
src/components/Tabbar/index.js
TongChia/react-alp
import React from 'react'; import './style.styl'; export default function Tabbar({ children }) { return ( <div className="tabbar"> {children} </div> ); }
tests/Rules-isInt-spec.js
sdemjanenko/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isInt" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with a number as string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="+42"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail string with digits': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="42 is an answer"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with an int': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a float': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={Math.PI}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should fail with a float in science notation': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="-1e3"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a zero': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); } };
examples/animations/app.js
tylermcginnis/react-router
import React from 'react' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import { render } from 'react-dom' import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' import './app.css' const App = ({ children, location }) => ( <div> <ul> <li><Link to="/page1">Page 1</Link></li> <li><Link to="/page2">Page 2</Link></li> </ul> <ReactCSSTransitionGroup component="div" transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={500} > {React.cloneElement(children, { key: location.pathname })} </ReactCSSTransitionGroup> </div> ) const Index = () => ( <div className="Image"> <h1>Index</h1> <p>Animations with React Router are not different than any other animation.</p> </div> ) const Page1 = () => ( <div className="Image"> <h1>Page 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) const Page2 = () => ( <div className="Image"> <h1>Page 2</h1> <p>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> ) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="page1" component={Page1} /> <Route path="page2" component={Page2} /> </Route> </Router> ), document.getElementById('example'))
examples/enzyme/CheckboxWithLabel.js
aaron-goshine/jest
// Copyright 2004-present Facebook. All Rights Reserved. import React from 'react'; export default class CheckboxWithLabel extends React.Component { constructor(props) { super(props); this.state = {isChecked: false}; // bind manually because React class components don't auto-bind // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding this.onChange = this.onChange.bind(this); } onChange() { this.setState({isChecked: !this.state.isChecked}); } render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } }
src/client/lib/menuHelper.js
andrerpena/monomock
import VNavItem from '../components/VNavItem'; import _ from 'underscore'; import React from 'react'; class MenuHelper { /** * Creates VNavItems from an Object containing nodes (each property in the nodes object represents a node) * @param nodes * @param onItemClick * @returns {*} */ createVNavItemsFromNodes(nodes, onItemClick) { if (!nodes) { return null; } return Object.keys(nodes).map((n, i) => this.createVNavItemFromNode(nodes[n], i, onItemClick)); } /** * Creates a VNavItem from a JSON node * @param node * @param key * @param onItemClick * @returns {XML} */ createVNavItemFromNode(node, key, onItemClick) { return <VNavItem key={key} node={node} onClick={onItemClick}/> } /** * Filter the given nodes. "nodes" is an object in which each property is a node * @param nodes * @param filterString */ filterNodes(nodes, filterString) { let result = {}; for (let node in nodes) { let filteredNode = this.filterNode(nodes[node], filterString); if (filteredNode) { result[node] = filteredNode; } } return result; } /** * Filters the given node and returns it. * @param node * @param filterString */ filterNode(node, filterString) { if (node.display.match(new RegExp(filterString, 'i'))) { return node; } else if (node.nodes) { let filteredChildren = this.filterNodes(node.nodes, filterString); if (Object.keys(filteredChildren).length) { node.nodes = filteredChildren; return node; } } return null; } } export default new MenuHelper();
src/svg-icons/av/library-books.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLibraryBooks = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"/> </SvgIcon> ); AvLibraryBooks = pure(AvLibraryBooks); AvLibraryBooks.displayName = 'AvLibraryBooks'; AvLibraryBooks.muiName = 'SvgIcon'; export default AvLibraryBooks;
packages/wix-style-react/src/EmptyState/test/EmptyState.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { visualize, snap, story } from 'storybook-snapper'; import EmptyState from '../EmptyState'; import ImagePlaceholder from '../../../stories/utils/ImagePlaceholder'; import { RTLWrapper } from '../../../stories/utils/RTLWrapper'; const commonProps = { title: "You don't have any items yet", subtitle: 'Create your product item in an easy & fast way to display it on your site', image: <ImagePlaceholder />, theme: 'page', }; const children = 'Consectetur tenetur enim impedit facilis assumenda Illum laborum delectus'; const tests = [ { describe: 'theme', its: [ { it: 'page', props: { theme: 'page', }, }, { it: 'page-no-border', props: { theme: 'page-no-border', }, }, { it: 'section', props: { theme: 'section', }, }, ], }, { describe: 'sanity', its: [ { it: 'no Title', props: { title: '', }, }, { it: 'no Subtitle', props: { subtitle: '', }, }, { it: 'no image', props: { image: '', }, }, ], }, { describe: 'alignment', its: [ { it: 'start', props: { align: 'start', }, }, { it: 'center', props: { align: 'center', }, }, { it: 'end', props: { align: 'end', }, }, ], }, { describe: 'with children', its: [ { it: 'start', props: { align: 'start', children, }, }, { it: 'center', props: { align: 'center', children, }, }, { it: 'end', props: { align: 'end', children, }, }, ], }, ]; const rtlTests = [ { describe: 'rtl', its: [ { it: 'start', props: { align: 'start', children, }, }, { it: 'center', props: { align: 'center', children, }, }, { it: 'end', props: { align: 'end', children, }, }, ], }, ]; export const runTests = ( { themeName, testWithTheme } = { testWithTheme: i => i }, ) => { visualize(`${themeName ? `${themeName}|` : ''}EmptyState`, () => { tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { story(describe, () => { snap(it, testWithTheme(<EmptyState {...commonProps} {...props} />)); }); }); }); rtlTests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { story(describe, () => { snap( it, testWithTheme( <RTLWrapper rtl> <EmptyState {...commonProps} {...props} /> </RTLWrapper>, ), ); }); }); }); }); };
site/components/PageBody.js
colbyr/react-dnd
import React from 'react'; import './PageBody.less'; export default class PageBody { static propTypes = { hasSidebar: React.PropTypes.bool }; render() { var {hasSidebar, html, ...props} = this.props; return ( <div className={`PageBody ${hasSidebar ? 'PageBody--hasSidebar' : ''}`}> <div className="PageBody-container"> {this.props.children} </div> </div> ); } }
www/src/@docpocalypse/gatsby-theme/components/SideNavigation.js
jquense/react-formal
import React from 'react'; import sortBy from 'lodash/sortBy'; import groupBy from 'lodash/groupBy'; import SideNavigation, { usePageData, } from '@docpocalypse/gatsby-theme/src/components/SideNavigation'; function AppSideNavigation(props) { const { api } = usePageData(); const groupedByMembers = groupBy( api, (doc) => doc.tags.find((t) => t.name === 'memberof')?.value || 'none', ); return ( <SideNavigation.Panel {...props}> <nav> <ul> <SideNavigation.Item> <SideNavigation.Link to="/getting-started"> Getting Started </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Link to="/controllables"> Controlled Components </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Link to="/migration-v2"> Migrating to v2 </SideNavigation.Link> </SideNavigation.Item> <SideNavigation.Item> <SideNavigation.Header>API</SideNavigation.Header> <ul className="mb-4"> {sortBy(api, 'title') .filter((n) => !n.tags.find((t) => t.name === 'memberof')) .map((page) => ( <SideNavigation.Item key={page.title}> <SideNavigation.Link to={page.path}> {page.title} {groupedByMembers[page.title] && ( <ul> {sortBy(groupedByMembers[page.title], 'title').map( (sub) => ( <SideNavigation.Item key={sub.title}> <SideNavigation.Link to={sub.path}> {sub.title} </SideNavigation.Link> </SideNavigation.Item> ), )} </ul> )} </SideNavigation.Link> </SideNavigation.Item> ))} </ul> </SideNavigation.Item> </ul> </nav> </SideNavigation.Panel> ); } export default AppSideNavigation;
frontend/src/components/dialog/sysadmin-dialog/sysadmin-delete-member-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { gettext } from '../../../utils/constants'; import { seafileAPI } from '../../../utils/seafile-api'; import { Utils } from '../../../utils/utils'; import toaster from '../../toast'; const propTypes = { member: PropTypes.object.isRequired, groupID: PropTypes.string.isRequired, toggle: PropTypes.func.isRequired, onMemberChanged: PropTypes.func.isRequired }; class DeleteMemberDialog extends React.Component { constructor(props) { super(props); } deleteMember = () => { const userEmail = this.props.member.email; seafileAPI.sysAdminDeleteGroupMember(this.props.groupID, userEmail).then((res) => { if (res.data.success) { this.props.onMemberChanged(); this.props.toggle(); } }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } render() { let tipMessage = gettext('Are you sure you want to delete {placeholder} ?'); tipMessage = tipMessage.replace('{placeholder}', '<span class="op-target">' + Utils.HTMLescape(this.props.member.name) + '</span>'); return ( <Modal isOpen={true} toggle={this.props.toggle}> <ModalHeader toggle={this.props.toggle}>{gettext('Delete Member')}</ModalHeader> <ModalBody> <div dangerouslySetInnerHTML={{__html: tipMessage}}></div> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.deleteMember}>{gettext('Delete')}</Button> <Button color="secondary" onClick={this.props.toggle}>{gettext('Cancel')}</Button> </ModalFooter> </Modal> ); } } DeleteMemberDialog.propTypes = propTypes; export default DeleteMemberDialog;
node_modules/react-router/es/RouterContext.js
nockgish/gish
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; import invariant from 'invariant'; import React from 'react'; import getRouteParams from './getRouteParams'; import { ContextProvider } from './ContextUtils'; import { isReactChildren } from './RouteUtils'; var _React$PropTypes = React.PropTypes, array = _React$PropTypes.array, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = React.createClass({ displayName: 'RouterContext', mixins: [ContextProvider('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: React.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = getRouteParams(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if (isReactChildren(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : void 0; return element; } }); export default RouterContext;
src/entypo/ThumbsDown.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--ThumbsDown'; let EntypoThumbsDown = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M6.352,12.638c0.133,0.356-3.539,3.634-1.397,6.291c0.501,0.621,2.201-2.975,4.615-4.602c1.331-0.899,4.43-2.811,4.43-3.868V3.617C14,2.346,9.086,1,5.352,1C3.983,1,2,9.576,2,10.939C2,12.306,6.221,12.282,6.352,12.638z M15,12.543c0.658,0,3-0.4,3-3.123V4.572c0-2.721-2.342-3.021-3-3.021c-0.657,0,1,0.572,1,2.26v6.373C16,11.952,14.343,12.543,15,12.543z"/> </EntypoIcon> ); export default EntypoThumbsDown;
js/jqwidgets/demos/react/app/grid/nestedgrids/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { componentDidMount() { this.refs.myGrid.showrowdetails(1); } render() { let employeesSource = { datafields: [ { name: 'FirstName' }, { name: 'LastName' }, { name: 'Title' }, { name: 'Address' }, { name: 'City' } ], root: 'Employees', record: 'Employee', id: 'EmployeeID', datatype: 'xml', async: false, url: '../sampledata/employees.xml' }; let employeesAdapter = new $.jqx.dataAdapter(employeesSource, { autoBind: true }); let ordersSource = { datafields: [ { name: 'EmployeeID', type: 'string' }, { name: 'ShipName', type: 'string' }, { name: 'ShipAddress', type: 'string' }, { name: 'ShipCity', type: 'string' }, { name: 'ShipCountry', type: 'string' }, { name: 'ShippedDate', type: 'date' } ], root: 'Orders', record: 'Order', datatype: 'xml', url: '../sampledata/orderdetails.xml', async: false }; let ordersDataAdapter = new $.jqx.dataAdapter(ordersSource, { autoBind: true }); let orders = ordersDataAdapter.records; let nestedGrids = new Array(); let rowdetailstemplate = { rowdetails: '<div id="grid" style="margin: 10px;"></div>', rowdetailsheight: 220, rowdetailshidden: true }; let initrowdetails = (index, parentElement, gridElement, record) => { let id = record.uid.toString(); let grid = $($(parentElement).children()[0]); nestedGrids[index] = grid; let filtergroup = new $.jqx.filter(); let filter_or_operator = 1; let filtervalue = id; let filtercondition = 'equal'; let filter = filtergroup.createfilter('stringfilter', filtervalue, filtercondition); // fill the orders depending on the id. let ordersbyid = []; for (let m = 0; m < orders.length; m++) { let result = filter.evaluate(orders[m]['EmployeeID']); if (result) ordersbyid.push(orders[m]); } let orderssource = { datafields: [ { name: 'EmployeeID', type: 'string' }, { name: 'ShipName', type: 'string' }, { name: 'ShipAddress', type: 'string' }, { name: 'ShipCity', type: 'string' }, { name: 'ShipCountry', type: 'string' }, { name: 'ShippedDate', type: 'date' } ], id: 'OrderID', localdata: ordersbyid } let nestedGridAdapter = new $.jqx.dataAdapter(orderssource); if (grid != null) { grid.jqxGrid({ source: nestedGridAdapter, width: 780, height: 200, columns: [ { text: 'Ship Name', datafield: 'ShipName', width: 200 }, { text: 'Ship Address', datafield: 'ShipAddress', width: 200 }, { text: 'Ship City', datafield: 'ShipCity', width: 150 }, { text: 'Ship Country', datafield: 'ShipCountry', width: 150 }, { text: 'Shipped Date', datafield: 'ShippedDate', width: 200 } ] }); } } let photosRenderer = (row, column, value) => { let records = employeesAdapter.records; let name = records[row].FirstName; let imgurl = '../images/' + name.toLowerCase() + '.png'; let img = '<div style="background: white;"><img style="margin:2px; margin-left: 10px;" width="32" height="32" src="' + imgurl + '"></div>'; return img; } let renderer = (row, column, value) => { return '<span style="margin-left: 4px; margin-top: 9px; float: left;">' + value + '</span>'; } let columns = [ { text: 'Photo', width: 50, cellsrenderer: photosRenderer }, { text: 'First Name', datafield: 'FirstName', width: 100, cellsrenderer: renderer }, { text: 'Last Name', datafield: 'LastName', width: 100, cellsrenderer: renderer }, { text: 'Title', datafield: 'Title', width: 180, cellsrenderer: renderer }, { text: 'Address', datafield: 'Address', width: 300, cellsrenderer: renderer }, { text: 'City', datafield: 'City', width: 170, cellsrenderer: renderer } ]; return ( <JqxGrid ref='myGrid' width={850} height={350} source={employeesAdapter} rowdetails={true} rowsheight={35} initrowdetails={initrowdetails} rowdetailstemplate={rowdetailstemplate} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/containers/MainPage/index.js
crp2002/e-commerce-site
/* * MainPage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import NavBar from './NavBar'; import ShirtsContainer from './ShirtsContainer'; import Bar from './Bar'; export default class MainPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { shirtCategory: 'all', sleeveType: 'all', }; } render() { return ( <div> <NavBar /> <Bar /> <ShirtsContainer /> </div> ); } }
src/LinkHandler.js
taskworld/legendary-pancake
import { isPathnameStartingWithBasename, stripBasenameFromPathname } from './PathUtils' import PropTypes from 'prop-types' import React from 'react' // # LinkHandler {#LinkHandler} // // A `<div>` tag that handles link clicks. // export class LinkHandler extends React.Component { static contextTypes = { legendaryPancake: PropTypes.object } static propTypes = { children: PropTypes.node } render () { return <div onClick={this.onClick}>{this.props.children}</div> } onClick = (e) => { if (!e.isDefaultPrevented()) { for (let element = e.target; element; element = element.parentNode) { if (element.nodeType === 1 && element.nodeName === 'A') { this.handleLinkElement(e, element) break } } } } handleLinkElement (e, a) { if (a.protocol !== window.location.protocol) return if (a.host !== window.location.host) return if (!this.context.legendaryPancake) return if (!isPathnameStartingWithBasename(a.pathname)) return const pathname = stripBasenameFromPathname(a.pathname) if (!this.context.legendaryPancake.pathnameExists(pathname)) return this.handleLink(e, pathname) } handleLink (e, pathname) { if (e.metaKey) return if (e.shiftKey) return if (e.altKey) return if (e.ctrlKey) return if (e.button !== 0) return this.context.legendaryPancake.go(pathname) e.preventDefault() } } export default LinkHandler
test/pincreator-test.js
ResponsibleRye/responsiblerye
//chai import { assert, expect } from 'chai'; import should from 'chai/register-should'; //sinon import { spy } from 'sinon'; //enzyme import { mount, shallow, render } from 'enzyme'; //react utils import React from 'react'; import ReactTestUtils from 'react-addons-test-utils'; import ReactDOM from 'react-dom'; //react component import PinCreator from '../react-client/src/components/pincreator.jsx'; //material-ui import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import {GridList, GridTile} from 'material-ui/GridList'; import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff'; import ActionHome from 'material-ui/svg-icons/action/home'; import ActionRoom from 'material-ui/svg-icons/action/room'; import BeenHere from 'material-ui/svg-icons/maps/beenhere'; import Hotel from 'material-ui/svg-icons/maps/hotel'; import Camera from 'material-ui/svg-icons/maps/local-see'; import Terrain from 'material-ui/svg-icons/maps/terrain'; import Restaurant from 'material-ui/svg-icons/maps/restaurant'; import Bar from 'material-ui/svg-icons/maps/local-bar'; import Pizza from 'material-ui/svg-icons/maps/local-pizza'; import Train from 'material-ui/svg-icons/maps/train'; import Mall from 'material-ui/svg-icons/maps/local-mall'; import Grocery from 'material-ui/svg-icons/maps/local-grocery-store'; import {cyan500} from 'material-ui/styles/colors'; describe('PinCreator', () => { describe('mounting type tests', () => { it('renders correctly', () => { const wrapper = shallow(<PinCreator />); assert.isOk(wrapper); }); it('mounts onto DOM', () => { const wrapper = mount( <MuiThemeProvider> <PinCreator /> </MuiThemeProvider> ); expect(wrapper.contains( <PinCreator /> )).to.equal(true); }); it('should have a Grid List', () => { const wrapper = shallow(<PinCreator />); assert.isOk(wrapper.find('GridList').length); }); it('should have Grid Tiles', () => { const wrapper = shallow(<PinCreator />); assert.isOk(wrapper.find('GridTile').length); }); it('mounting adds to our html', () => { expect(mount( <MuiThemeProvider> <PinCreator /> </MuiThemeProvider> ).find('GridList').length).to.equal(1); }); it('PinCreator\'s GridTile should be capable of handling a touchTap', () => { const handleTouchTap = spy(); const wrapper = mount( <MuiThemeProvider> <PinCreator /> </MuiThemeProvider> ); wrapper.find('PinCreator').node.handle = handleTouchTap; wrapper.update(); ReactTestUtils.Simulate.touchTap(ReactDOM.findDOMNode(wrapper.find('GridTile').node)); expect(handleTouchTap.calledOnce).to.equal(true); }); }); });
src/svg-icons/action/shop-two.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShopTwo = (props) => ( <SvgIcon {...props}> <path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9zm15-4V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm0 12V8l5.5 3-5.5 4z"/> </SvgIcon> ); ActionShopTwo = pure(ActionShopTwo); ActionShopTwo.displayName = 'ActionShopTwo'; ActionShopTwo.muiName = 'SvgIcon'; export default ActionShopTwo;
pages/less.js
adjohnson916/site-gatsby
import React from 'react' import './example.less' export default class Less extends React.Component { render () { return ( <div> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> ) } }
src/common/components/Appbar/jsPsychInitEditor/index.js
jspsych/jsPsych-Redux-GUI
import React from 'react'; import Dialog from 'material-ui/Dialog'; import Subheader from 'material-ui/Subheader'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import TextField from 'material-ui/TextField'; import { grey800 as normalColor, cyan500 as iconHighlightColor, green500 as checkColor, blue500 as titleIconColor } from 'material-ui/styles/colors'; import InitSettingIcon from 'material-ui/svg-icons/action/build'; import CheckIcon from 'material-ui/svg-icons/toggle/radio-button-checked'; import UnCheckIcon from 'material-ui/svg-icons/toggle/radio-button-unchecked'; import CodeEditor from '../../CodeEditor'; import { renderDialogTitle } from '../../gadgets'; import { settingType } from '../../../reducers/Experiment/jsPsychInit'; import AppbarTheme from '../theme.js'; const colors = { ...AppbarTheme.colors } const style = { Icon: AppbarTheme.AppbarIcon, TitleIcon: { color: colors.primaryDeep }, TextFieldFocusStyle: { ...AppbarTheme.TextFieldFocusStyle() }, Actions: { Close: { labelStyle: { color: colors.secondaryDeep } } } } export default class jsPsychInitEditor extends React.Component { constructor(props) { super(props); this.state = { open: false } this.handleOpen = () => { this.setState({ open: true }); }; this.handleClose = () => { this.setState({ open: false }); }; this.textFieldRow = (key, type="number", unit=null) => ( <div style={{display: 'flex'}}> <div style={{padding: 15, color: 'black'}}>{key + ((unit) ? " (" + unit + ")" : "")}: </div> <TextField {...style.TextFieldFocusStyle} id={"text-field-"+key} value={this.props[key]} type={type} onChange={(e, value) => { this.props.setJsPsychInit(e, value, key); }} /> </div> ) this.toggleRow = (key) => ( <div style={{display: 'flex', width: 370, position: 'relative'}}> <div style={{padding: 15, color: 'black'}}>{key}</div> <IconButton style={{position: 'absolute', right: 0}} onClick={() => { this.props.setJsPsychInit(null, null, key); }} > {(this.props[key]) ? <CheckIcon color={checkColor} /> : <UnCheckIcon />}/> </IconButton> </div> ) this.codeRow = (key) => ( <div style={{display: 'flex', width: 370, position: 'relative'}}> <div style={{padding: 15, color: 'black'}}>{key}</div> <div style={{position: 'absolute', right: 0}}> <CodeEditor value={this.props[key].code} onlyFunction={true} onCommit={(newCode) => { this.props.setJsPsychInit(null, newCode, key); }} title={key+": "} /> </div> </div> ) } render() { const actions = [ ]; return ( <div className="jsPsych.init-editor"> <IconButton tooltip="Init Properties Setting" onClick={this.handleOpen} > <InitSettingIcon {...style.Icon}/> </IconButton> <Dialog contentStyle={{minHeight: 500}} titleStyle={{padding: 0}} title={ renderDialogTitle( <Subheader style={{maxHeight: 48}}> <div style={{display: 'flex'}}> <div style={{paddingTop: 8, paddingRight: 15}}> <InitSettingIcon {...style.TitleIcon}/> </div> <div style={{fontSize: 16,}}> jsPsych.init properties </div> </div> </Subheader>, this.handleClose, null) } actions={actions} modal={true} open={this.state.open} onRequestClose={this.handleClose} autoScrollBodyContent={true} > {this.textFieldRow(settingType.default_iti)} {this.codeRow(settingType.on_finish)} {this.codeRow(settingType.on_trial_start)} {this.codeRow(settingType.on_trial_finish)} {this.codeRow(settingType.on_data_update)} {this.codeRow(settingType.on_interaction_data_update)} {this.toggleRow(settingType.show_progress_bar)} {this.toggleRow(settingType.auto_update_progress_bar)} {this.toggleRow(settingType.show_preload_progress_bar)} <div style={{padding: 15}}>preload_audio: </div> <div style={{padding: 15}}>preload_images: </div> {this.textFieldRow(settingType.max_load_time, "number", "ms")} <div style={{padding: 15}}>Exclusions: </div> <div style={{paddingLeft: 32}}> {this.textFieldRow(settingType.min_width)} {this.textFieldRow(settingType.min_height)} {this.toggleRow(settingType.audio)} </div> </Dialog> </div> ) } }
src/svg-icons/image/flip.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlip = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z"/> </SvgIcon> ); ImageFlip = pure(ImageFlip); ImageFlip.displayName = 'ImageFlip'; ImageFlip.muiName = 'SvgIcon'; export default ImageFlip;
react-flux-mui/js/material-ui/src/svg-icons/maps/directions-railway.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsRailway = (props) => ( <SvgIcon {...props}> <path d="M4 15.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5zm8 1.5c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6-7H6V5h12v5z"/> </SvgIcon> ); MapsDirectionsRailway = pure(MapsDirectionsRailway); MapsDirectionsRailway.displayName = 'MapsDirectionsRailway'; MapsDirectionsRailway.muiName = 'SvgIcon'; export default MapsDirectionsRailway;
src/components/__tests__/InfoBar-test.js
vidaaudrey/mindr
import React from 'react'; import ReactDOM from 'react-dom'; import {renderIntoDocument} from 'react-addons-test-utils'; import { expect} from 'chai'; import { InfoBar } from 'components'; import { Provider } from 'react-redux'; import {reduxReactRouter} from 'redux-router'; import createHistory from 'history/lib/createMemoryHistory'; import createStore from 'redux/create'; import ApiClient from 'helpers/ApiClient'; const client = new ApiClient(); describe('InfoBar', () => { const mockStore = { info: { load: () => {}, loaded: true, loading: false, data: { message: 'This came from the api server', time: Date.now() } } }; const store = createStore(reduxReactRouter, null, createHistory, client, mockStore); const renderer = renderIntoDocument( <Provider store={store} key="provider"> <InfoBar/> </Provider> ); const dom = ReactDOM.findDOMNode(renderer); it('should render correctly', () => { return expect(renderer).to.be.ok; }); it('should render with correct value', () => { const text = dom.getElementsByTagName('strong')[0].textContent; expect(text).to.equal(mockStore.info.data.message); }); it('should render with a reload button', () => { const text = dom.getElementsByTagName('button')[0].textContent; expect(text).to.be.a('string'); }); it('should render the correct className', () => { const styles = require('components/InfoBar/InfoBar.scss'); expect(styles.infoBar).to.be.a('string'); expect(dom.className).to.include(styles.infoBar); }); });
node_modules/react-router/es/withRouter.js
mohammed52/something.pk
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { ContextSubscriber } from './ContextUtils'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; if (!router) { return React.createElement(WrappedComponent, this.props); } var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
src/js/components/plan/EditPlan.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { connect } from 'react-redux'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import { ModalHeader, ModalTitle } from 'react-bootstrap'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import React from 'react'; import { Redirect } from 'react-router-dom'; import { CloseModalXButton, RoutedModal } from '../ui/Modals'; import { getPlan, getPlanFiles, getIsLoadingPlan } from '../../selectors/plans'; import { fetchPlanFiles, updatePlan, updatePlanFromGit, updatePlanFromTarball } from '../../actions/PlansActions'; import EditPlanForm from './EditPlanForm'; import EditPlanFormTabs from './EditPlanFormTabs'; import { Loader } from '../ui/Loader'; import { planTransitionMessages } from '../../constants/PlansConstants'; const messages = defineMessages({ cancel: { id: 'EditPlan.cancel', defaultMessage: 'Cancel' }, editPlan: { id: 'EditPlan.editPlan', defaultMessage: 'Edit {planName} plan' } }); class EditPlan extends React.Component { componentDidMount() { this.props.fetchPlanFiles(this.props.match.params.planName); } handleFormSubmit = ( { planName, planUploadType, files, tarball, gitUrl }, dispatch, props ) => { switch (planUploadType) { case 'tarball': return this.props.updatePlanFromTarball(planName, tarball); case 'directory': let planFiles = {}; files.map(({ filePath, contents }) => (planFiles[filePath] = contents)); return this.props.updatePlan(planName, planFiles); case 'git': return this.props.updatePlanFromGit(planName, gitUrl); default: return null; } }; render() { const { plan, planFiles, intl: { formatMessage }, isLoadingPlan } = this.props; return plan ? ( <RoutedModal bsSize="lg" id="EditPlan__modal" redirectPath="/plans/manage" > <ModalHeader> <CloseModalXButton /> <ModalTitle> <FormattedMessage {...messages.editPlan} values={{ planName: plan.name }} /> </ModalTitle> </ModalHeader> <Loader loaded={!isLoadingPlan} size="lg" height={60} content={formatMessage(planTransitionMessages.loading, { planName: plan.name })} > <EditPlanForm onSubmit={this.handleFormSubmit} initialValues={{ planName: plan.name, planUploadType: 'directory', files: [] }} > <EditPlanFormTabs planName={plan.name} planFiles={planFiles} /> </EditPlanForm> </Loader> </RoutedModal> ) : ( <Redirect to="/plans" /> ); } } EditPlan.propTypes = { fetchPlanFiles: PropTypes.func, intl: PropTypes.object, isLoadingPlan: PropTypes.bool.isRequired, match: PropTypes.object, plan: ImmutablePropTypes.record, planFiles: ImmutablePropTypes.set.isRequired, updatePlan: PropTypes.func.isRequired, updatePlanFromGit: PropTypes.func.isRequired, updatePlanFromTarball: PropTypes.func.isRequired }; const mapStateToProps = (state, { match: { params: { planName } } }) => ({ plan: getPlan(state, planName), planFiles: getPlanFiles(state, planName), isLoadingPlan: getIsLoadingPlan(state, planName) }); const mapDispatchToProps = (dispatch, ownProps) => ({ fetchPlanFiles: planName => { dispatch(fetchPlanFiles(planName)); }, updatePlan: (planName, files) => { dispatch(updatePlan(planName, files)); }, updatePlanFromTarball: (planName, files) => { dispatch(updatePlanFromTarball(planName, files)); }, updatePlanFromGit: (planName, gitUrl) => { dispatch(updatePlanFromGit(planName, gitUrl)); } }); export default injectIntl( connect(mapStateToProps, mapDispatchToProps)(EditPlan) );
frontend/src/components/dialog/sysadmin-dialog/sysadmin-set-org-max-user-number-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Alert, Modal, ModalHeader, ModalBody, ModalFooter, Button, Form, FormGroup, Input, InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap'; import { gettext } from '../../../utils/constants'; import { Utils } from '../../../utils/utils'; const propTypes = { toggle: PropTypes.func.isRequired, updateValue: PropTypes.func.isRequired }; class SysAdminSetOrgMaxUserNumberDialog extends React.Component { constructor(props) { super(props); this.state = { value: this.props.value, isSubmitBtnActive: false }; } toggle = () => { this.props.toggle(); } handleInputChange = (e) => { const value = e.target.value; this.setState({ value: value, isSubmitBtnActive: value.trim() != '' }); } handleKeyPress = (e) => { if (e.key == 'Enter') { this.handleSubmit(); e.preventDefault(); } } handleSubmit = () => { this.props.updateValue(this.state.value.trim()); this.toggle(); } render() { const { value, isSubmitBtnActive } = this.state; return ( <Modal isOpen={true} toggle={this.toggle}> <ModalHeader toggle={this.toggle}>{gettext('Set max number of members')}</ModalHeader> <ModalBody> <Form> <FormGroup> <Input type="text" className="form-control" value={value} onKeyPress={this.handleKeyPress} onChange={this.handleInputChange} /> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggle}>{gettext('Cancel')}</Button> <Button color="primary" onClick={this.handleSubmit} disabled={!isSubmitBtnActive}>{gettext('Submit')}</Button> </ModalFooter> </Modal> ); } } SysAdminSetOrgMaxUserNumberDialog.propTypes = propTypes; export default SysAdminSetOrgMaxUserNumberDialog;
app/containers/App/index.js
keithalpichi/NobleNote
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> <h2>Header here- Place Header Component in App Container</h2> {React.Children.toArray(this.props.children)} <h2>Footer here</h2> </div> ); } }
submissions/winstonewert/src/root.js
winstonewert/flux-challenge
import React from 'react' import ObiWanPlanetMonitor from './obi-wan-planet-monitor' import DarkJediList from './dark-jedi-list' export default class Root extends React.Component { render() { return <div className="app-container"> <div className="css-root"> <ObiWanPlanetMonitor /> <DarkJediList /> </div> </div> } }
src/components/Snake/Body.js
nataly87s/rx-snake
import React from 'react'; import glamorous from 'glamorous'; import { SOLUTO_BLUE } from '../../resources/colors'; const Circle = glamorous.circle({ opacity: 0.4, }); const BodySvg = ({ style, color = SOLUTO_BLUE }) => ( <svg x="0px" y="0px" viewBox="0 0 77 77" style={style}> <path fill="#FFFFFF" d="M27.3,72.7c-12.7,0-23-10.3-23-23V27.3c0-12.7,10.3-23,23-23h22.5c12.7,0,23,10.3,23,23v22.5 c0,12.7-10.3,23-23,23H27.3z"/> <path fill={color} d="M49.7,8.3c10.5,0,19,8.5,19,19v22.5c0,10.5-8.5,19-19,19H27.3c-10.5,0-19-8.5-19-19V27.3c0-10.5,8.5-19,19-19H49.7 M49.7,0.3H27.3c-14.9,0-27,12.2-27,27v22.5c0,14.8,12.1,27,27,27h22.5c14.8,0,27-12.2,27-27V27.3C76.7,12.4,64.6,0.3,49.7,0.3 L49.7,0.3z"/> <Circle fill={color} cx="38.5" cy="38.5" r="21.8"/> </svg> ); export default BodySvg;
app/containers/settings/index.js
7kfpun/TWAQIReactNative
import React, { Component } from 'react'; import { FlatList, Platform, StyleSheet, Text, View } from 'react-native'; import { iOSColors } from 'react-native-typography'; import Collapsible from 'react-native-collapsible'; import DeviceInfo from 'react-native-device-info'; import OneSignal from 'react-native-onesignal'; import Search from 'react-native-search-box'; import Fuse from 'fuse.js'; import AdMob from '../../components/admob'; import SettingsGroup from '../../components/settings-group'; import SettingsItem from '../../components/settings-item'; import SwipeScrollView from '../../components/swipe-scroll-view'; import SettingsDND from './components/settings-dnd'; import { countys, locations } from '../../utils/locations'; import { OneSignalGetTags } from '../../utils/onesignal'; import I18n from '../../utils/i18n'; const CHECK_INTERVAL = 60 * 1000; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, titleBlock: { paddingTop: Platform.OS === 'ios' ? 60 : 20, paddingLeft: 10, }, titleText: { fontSize: 24, color: 'black', }, permissionReminderBlock: { backgroundColor: '#3949AB', justifyContent: 'center', alignItems: 'center', padding: 1, }, permissionReminderText: { fontSize: 12, color: 'white', }, searchBlock: { padding: 10, paddingTop: 20, borderBottomColor: iOSColors.lightGray, borderBottomWidth: 1, }, list: { paddingVertical: 30, }, }); export default class SettingsView extends Component { static requestPermissions() { if (Platform.OS === 'ios') { const permissions = { alert: true, badge: true, sound: true, }; OneSignal.requestPermissions(permissions); OneSignal.registerForPushNotifications(); } } state = { isShowPermissionReminderBlock: false, searchText: '', searchResult: [], collapsed: false, }; componentDidMount() { // Request permission on start SettingsView.requestPermissions(); this.loadEnabledItems(); this.loadEnabledItemsInterval = setInterval( () => this.loadEnabledItems(), CHECK_INTERVAL, ); } componentWillUnmount() { if (this.loadEnabledItemsInterval) clearInterval(this.loadEnabledItemsInterval); if (this.checkPermissionsInterval) clearInterval(this.checkPermissionsInterval); } onChangeText = (searchText) => { const options = { shouldSort: true, threshold: 0.2, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, keys: [ 'SiteName', 'SiteEngName', 'AreaName', 'County', 'Township', 'SiteAddress', ], }; const fuse = new Fuse(locations, options); const searchResult = fuse.search(searchText); this.setState({ searchText, searchResult }); }; onCancelOrDelete = () => { this.setState({ searchText: '' }); }; checkPermissions(tags) { if ( Platform.OS === 'ios' && tags && Object.values(tags).indexOf('true') !== -1 ) { OneSignal.checkPermissions((permissions) => { console.log('checkPermissions', permissions); if (!permissions || (permissions && !permissions.alert)) { this.setState({ isShowPermissionReminderBlock: true }); } else { this.setState({ isShowPermissionReminderBlock: false }); } }); SettingsView.requestPermissions(); } } async loadEnabledItems() { const tags = await OneSignalGetTags(); if (JSON.stringify(tags) !== JSON.stringify(this.state.tags)) { this.setState({ tags, k: Math.random() }); } this.checkPermissions(tags); this.checkPermissionsInterval = setInterval( () => this.checkPermissions(tags), CHECK_INTERVAL, ); } render() { const { collapsed, isShowPermissionReminderBlock, searchResult, searchText, tags, } = this.state; return ( <View style={styles.container}> <Collapsible collapsed={collapsed}> <View style={styles.titleBlock}> <Text style={styles.titleText}>{I18n.t('notify_title')}</Text> </View> </Collapsible> <View style={[ styles.searchBlock, { marginTop: collapsed && DeviceInfo.hasNotch() ? 20 : 0 }, ]} > <Search backgroundColor={iOSColors.white} titleCancelColor={iOSColors.blue} onChangeText={this.onChangeText} onCancel={this.onCancelOrDelete} onDelete={this.onCancelOrDelete} cancelTitle={I18n.t('cancel')} placeholder={I18n.t('search')} /> </View> {isShowPermissionReminderBlock && ( <View style={styles.permissionReminderBlock}> <Text style={styles.permissionReminderText}> {I18n.t('permissions_required')} </Text> </View> )} <SwipeScrollView scrollActionOffset={80} onScrollUp={() => this.setState({ collapsed: true })} onScrollDown={() => this.setState({ collapsed: false })} > {!!searchText && ( <FlatList key={this.state.k} style={styles.list} data={searchResult} keyExtractor={(item, index) => `${index}-${item}`} renderItem={({ item }) => ( <View style={{ paddingHorizontal: 10 }}> <SettingsItem item={item} tags={tags} /> </View> )} /> )} {!searchText && ( <View key={this.state.k}> <SettingsDND tags={tags} /> <FlatList style={styles.list} data={countys} keyExtractor={(item, index) => `${index}-${item}`} renderItem={({ item }) => ( <SettingsGroup groupName={item} tags={tags} onToggle={() => this.loadEnabledItems()} /> )} /> </View> )} </SwipeScrollView> <AdMob unitId={`twaqi-${Platform.OS}-settings-footer`} /> </View> ); } }
src/svg-icons/hardware/keyboard-hide.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardHide = (props) => ( <SvgIcon {...props}> <path d="M20 3H4c-1.1 0-1.99.9-1.99 2L2 15c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 3h2v2h-2V6zm0 3h2v2h-2V9zM8 6h2v2H8V6zm0 3h2v2H8V9zm-1 2H5V9h2v2zm0-3H5V6h2v2zm9 7H8v-2h8v2zm0-4h-2V9h2v2zm0-3h-2V6h2v2zm3 3h-2V9h2v2zm0-3h-2V6h2v2zm-7 15l4-4H8l4 4z"/> </SvgIcon> ); HardwareKeyboardHide = pure(HardwareKeyboardHide); HardwareKeyboardHide.displayName = 'HardwareKeyboardHide'; export default HardwareKeyboardHide;
app/javascript/mastodon/features/ui/components/columns_area.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import { links, getIndex, getLink } from './tabs_bar'; import { Link } from 'react-router-dom'; import BundleContainer from '../containers/bundle_container'; import ColumnLoading from './column_loading'; import DrawerLoading from './drawer_loading'; import BundleColumnError from './bundle_column_error'; import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components'; import detectPassiveEvents from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'DIRECT': DirectTimeline, 'FAVOURITES': FavouritedStatuses, 'LIST': ListTimeline, }; const messages = defineMessages({ publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, }); const shouldHideFAB = path => path.match(/^\/statuses\/|^\/search|^\/getting-started/); export default @(component => injectIntl(component, { withRef: true })) class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, columns: ImmutablePropTypes.list.isRequired, isModalOpen: PropTypes.bool.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; state = { shouldAnimate: false, } componentWillReceiveProps() { this.setState({ shouldAnimate: false }); } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl'); this.setState({ shouldAnimate: true }); } componentWillUpdate(nextProps) { if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } componentDidUpdate(prevProps) { if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.setState({ shouldAnimate: true }); } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } handleChildrenContentChange() { if (!this.props.singleColumn) { const modifier = this.isRtlLayout ? -1 : 1; this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier); } } handleSwipe = (index) => { this.pendingIndex = index; const nextLinkTranslationId = links[index].props['data-preview-title-id']; const currentLinkSelector = '.tabs-bar__link.active'; const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`; // HACK: Remove the active class from the current link and set it to the next one // React-router does this for us, but too late, feeling laggy. document.querySelector(currentLinkSelector).classList.remove('active'); document.querySelector(nextLinkSelector).classList.add('active'); } handleAnimationEnd = () => { if (typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = (node) => { this.node = node; } renderView = (link, index) => { const columnIndex = getIndex(this.context.router.history.location.pathname); const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] }); const icon = link.props['data-preview-icon']; const view = (index === columnIndex) ? React.cloneElement(this.props.children) : <ColumnLoading title={title} icon={icon} />; return ( <div className='columns-area' key={index}> {view} </div> ); } renderLoading = columnId => () => { return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { columns, children, singleColumn, isModalOpen, intl } = this.props; const { shouldAnimate } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); this.pendingIndex = null; if (singleColumn) { const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><i className='fa fa-pencil' /></Link>; return columnIndex !== -1 ? [ <ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}> {links.map(this.renderView)} </ReactSwipeableViews>, floatingActionButton, ] : [ <div className='columns-area'>{children}</div>, floatingActionButton, ]; } return ( <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}> {columns.map(column => { const params = column.get('params', null) === null ? null : column.get('params').toJS(); const other = params && params.other ? params.other : {}; return ( <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}> {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />} </BundleContainer> ); })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
src/routes/Counter/components/Counter.js
codingarchitect/react-counter-pair
import React from 'react' import PropTypes from 'prop-types' import Counter from './counter.rt'; Counter.propTypes = { value : PropTypes.number.isRequired, onIncrement : PropTypes.func.isRequired, onDecrement : PropTypes.func.isRequired } export default Counter;
frontend/Views/NotFound/index.js
shoumma/ReForum
import React, { Component } from 'react'; class NotFound extends Component { render() { return ( <h3>Coudn't found the url buddy. Please check it out.</h3> ); } } export default NotFound;
components/animals/araArarauna.adult.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/araArarauna/01.jpg'), require('../../images/animals/araArarauna/02.jpg'), require('../../images/animals/araArarauna/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/araArarauna/01-thumb.jpg'), require('../../images/animals/araArarauna/02-thumb.jpg'), require('../../images/animals/araArarauna/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Tento druh papouška je asi nejznámější a nejoblíbenější ze všech arů. Má totiž velmi dobré vlastnosti pro ochočení. Je vysoce inteligentní, a pokud k&nbsp;člověku přilne, vyžaduje jeho pozornost. </AnimalText> <AnimalText> Brněnská zoologická zahrada se může pyšnit prvním odchovem ary ararauny na českém území, a to v&nbsp;roce 1963. Nyní se tito ptáci nachází v&nbsp;expozici zvané Exotárium, kde mají možnost vyžití jak venku, tak uvnitř. Tudíž pokud je nevidíte venku, jsou uvnitř a naopak. Rádi mezi těmito místy přelétávají. Momentálně zde bydlí samička Koko, její partner Pedro a ještě tu máme samečka Edu. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Papoušci ara mají nenápadné krycí zbarvení, spodní část těla je žlutá a vrchní zelenomodrá. Když se schovávají v&nbsp;korunách stromů a svítí slunce, jsou proti modré obloze téměř k&nbsp;nenalezení. Na krku mají černý pruh, okolí očí je, až na pár černých pírek, bílé a holé. Měří mezi 80–86&nbsp;centimetry, ale většinu této délky zaujímá dlouhý ocas. Pohlaví se nedá určit ani podle vnějšího zbarvení, ani podle chování, ale pouze za pomoci vyšetření. Zobák mají černý, mohutný a zahnutý. Jeho spodní část je pohyblivá. </AnimalText> <AnimalText> Díky silnému zobáku nemají problém rozlousknout jakkoli tvrdou skořápku. Jejich nejčastější potravou jsou různé druhy ořechů, plody, pupeny, mladé výhonky stromů a příležitostně hmyz. Za potravou jsou schopni létat až 25&nbsp;kilometrů daleko v&nbsp;hejnech, která vedou vždy starší a zkušenější ptáci. Pohromadě také létají ke břehům řek, kde požírají jíl kvůli neutralizaci rostlinných toxinů z&nbsp;potravy. Hledat jídlo se vydávají za úsvitu, za soumraku se pak shromažďují v&nbsp;dutinách stromů, kde tráví noc. </AnimalText> <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Samička snáší 1–3&nbsp;vejce, na kterých sedí cca 25&nbsp;dní. Mláďata se rodí holá a slepá, peří jim narůstá až za 10&nbsp;týdnů, dospívají ve 2–3&nbsp;letech. Malé ary krmí samec. Pokud se k&nbsp;hnízdu přiblíží vetřelec, oba rodiče bývají velmi agresivní. Žijí v&nbsp;monogamních párech, pokud nehnízdí, tak i&nbsp;v&nbsp;hejnech. Dožívají se asi 50&nbsp;let, v&nbsp;lidské péči až 80&nbsp;let. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
packages/core/content-type-builder/admin/src/components/TextareaEnum/index.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { useIntl } from 'react-intl'; import { Textarea } from '@strapi/design-system/Textarea'; const TextareaEnum = ({ description, disabled, error, intlLabel, labelAction, name, onChange, placeholder, value, }) => { const { formatMessage } = useIntl(); const errorMessage = error ? formatMessage({ id: error, defaultMessage: error }) : ''; const hint = description ? formatMessage( { id: description.id, defaultMessage: description.defaultMessage }, { ...description.values } ) : ''; const label = formatMessage(intlLabel); const formattedPlaceholder = placeholder ? formatMessage( { id: placeholder.id, defaultMessage: placeholder.defaultMessage }, { ...placeholder.values } ) : ''; const inputValue = Array.isArray(value) ? value.join('\n') : ''; const handleChange = e => { const arrayValue = e.target.value.split('\n'); onChange({ target: { name, value: arrayValue } }); }; return ( <Textarea disabled={disabled} error={errorMessage} label={label} labelAction={labelAction} id={name} hint={hint} name={name} onChange={handleChange} placeholder={formattedPlaceholder} value={inputValue} > {inputValue} </Textarea> ); }; TextareaEnum.defaultProps = { description: null, disabled: false, error: '', labelAction: undefined, placeholder: null, value: '', }; TextareaEnum.propTypes = { description: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), disabled: PropTypes.bool, error: PropTypes.string, intlLabel: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }).isRequired, labelAction: PropTypes.element, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, placeholder: PropTypes.shape({ id: PropTypes.string.isRequired, defaultMessage: PropTypes.string.isRequired, values: PropTypes.object, }), value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]), }; export default TextareaEnum;
src/templates/landing.js
gabrielcsapo/tryitout
import 'psychic.css/dist/psychic.min.css' import './landing.css' import React from 'react' import PropTypes from 'prop-types' import { render } from 'react-dom' import HTML from '../HTML' import { cleanString } from '../../lib/util' class Landing extends React.Component { render () { const { title, nav, body, footer, options } = this.props const { width } = options // Set the title of the window document.title = title return ( <div id='container' style={{ width, textAlign: 'center' }}> <div className='navbar'> <div className='container'> <div className='navbar-title'><span className='text-black'>{cleanString(title)}</span></div> <div className='nav'> {Object.keys(nav).map((k, i) => { return <a key={i} href={nav[k]} target='_blank' rel='noopener noreferrer'> {k} </a> })} </div> </div> </div> <div id='container-content'> <div style={{ margin: '0 auto' }}> <HTML value={body} /> </div> </div> <div className='footer'> <HTML value={footer} /> </div> </div> ) } } Landing.propTypes = { title: PropTypes.string, body: PropTypes.body, nav: PropTypes.array, options: PropTypes.shape({ width: PropTypes.string }), footer: PropTypes.string } Landing.defaultProps = { title: '', body: '', nav: [], options: { width: '90%' }, footer: '' } if ((window && window.config) || global.config) { const injectedConfig = (window && window.config) || global.config render(<Landing {...injectedConfig} />, document.getElementById('root')) if (injectedConfig.dev) { const hash = injectedConfig.hash setInterval(function () { const xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { const response = JSON.parse(xhttp.responseText) if (response.hash !== hash) { location.reload() } } } xhttp.open('GET', '/update', true) xhttp.send() }, 5000) } } else { module.exports = Landing }
Root.js
praida/admin
import React from 'react'; import PropTypes from 'prop-types'; import { IntlProvider } from 'react-intl'; import { Provider } from 'react-redux'; import './styles/normalize.scss'; import './styles/default.scss'; import './styles/layout.scss'; import Routes from './Routes'; const Root = props => ( <IntlProvider locale="en"> <Provider store={props.store}> <Routes /> </Provider> </IntlProvider> ); Root.propTypes = { store: PropTypes.object.isRequired, }; export default Root;
src/interface/common/Alert/index.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; class Alert extends React.PureComponent { static propTypes = { kind: PropTypes.oneOf(['danger', 'warning', 'info']), children: PropTypes.node.isRequired, className: PropTypes.string, }; render() { const { kind, children, className, ...others } = this.props; return ( <div className={`alert alert-${kind} ${className || ''}`} {...others}> {children} </div> ); } } export default Alert;
app/javascript/flavours/glitch/features/ui/components/image_loader.js
vahnj/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class ImageLoader extends React.PureComponent { static propTypes = { alt: PropTypes.string, src: PropTypes.string.isRequired, previewSrc: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number, } static defaultProps = { alt: '', width: null, height: null, }; state = { loading: true, error: false, } removers = []; get canvasContext() { if (!this.canvas) { return null; } this._canvasContext = this._canvasContext || this.canvas.getContext('2d'); return this._canvasContext; } componentDidMount () { this.loadImage(this.props); } componentWillReceiveProps (nextProps) { if (this.props.src !== nextProps.src) { this.loadImage(nextProps); } } loadImage (props) { this.removeEventListeners(); this.setState({ loading: true, error: false }); Promise.all([ this.loadPreviewCanvas(props), this.hasSize() && this.loadOriginalImage(props), ].filter(Boolean)) .then(() => { this.setState({ loading: false, error: false }); this.clearPreviewCanvas(); }) .catch(() => this.setState({ loading: false, error: true })); } loadPreviewCanvas = ({ previewSrc, width, height }) => new Promise((resolve, reject) => { const image = new Image(); const removeEventListeners = () => { image.removeEventListener('error', handleError); image.removeEventListener('load', handleLoad); }; const handleError = () => { removeEventListeners(); reject(); }; const handleLoad = () => { removeEventListeners(); this.canvasContext.drawImage(image, 0, 0, width, height); resolve(); }; image.addEventListener('error', handleError); image.addEventListener('load', handleLoad); image.src = previewSrc; this.removers.push(removeEventListeners); }) clearPreviewCanvas () { const { width, height } = this.canvas; this.canvasContext.clearRect(0, 0, width, height); } loadOriginalImage = ({ src }) => new Promise((resolve, reject) => { const image = new Image(); const removeEventListeners = () => { image.removeEventListener('error', handleError); image.removeEventListener('load', handleLoad); }; const handleError = () => { removeEventListeners(); reject(); }; const handleLoad = () => { removeEventListeners(); resolve(); }; image.addEventListener('error', handleError); image.addEventListener('load', handleLoad); image.src = src; this.removers.push(removeEventListeners); }); removeEventListeners () { this.removers.forEach(listeners => listeners()); this.removers = []; } hasSize () { const { width, height } = this.props; return typeof width === 'number' && typeof height === 'number'; } setCanvasRef = c => { this.canvas = c; } render () { const { alt, src, width, height } = this.props; const { loading } = this.state; const className = classNames('image-loader', { 'image-loader--loading': loading, 'image-loader--amorphous': !this.hasSize(), }); return ( <div className={className}> <canvas className='image-loader__preview-canvas' width={width} height={height} ref={this.setCanvasRef} style={{ opacity: loading ? 1 : 0 }} /> {!loading && ( <img alt={alt} className='image-loader__img' src={src} width={width} height={height} /> )} </div> ); } }
src/pages/PrivacyPage.js
neontribe/gbptm
import React from 'react'; import { Helmet } from 'react-helmet'; import PageLayout from '../components/PageLayout'; import Container from '../components/Container'; import Text from '../components/Text'; import Spacer from '../components/Spacer'; import Button from '../components/Button'; import config from '../config'; const PrivacyPage = () => { return ( <PageLayout layoutMode="blog"> <Helmet> <title>{config.getTitle('Privacy Policy')}</title> </Helmet> <Container maxWidth={845}> <Text fontSize={6} fontWeight="bold" textAlign="center"> <h1>Privacy Policy</h1> </Text> <Spacer mb={5} /> <Text fontSize={3} fontWeight="bold"> <h2>Visitors to the site</h2> </Text> <Spacer mb={3} /> <p> The Great British Public Toilet Map uses a cookieless approach to gather anonymous data such as which pages are viewed, what time the visit occurred, and which site referred the visitor to the web page etc. </p> <p> Public Convenience Ltd also notes and saves information such as time of day, browser type and content requested. That information is used to provide more relevant services to users. </p> <p> We will not associate any data gathered from this site through navigation and with any personally identifying information from any source. We may also log Internet Protocol (IP) address (but nothing that directly identifies visitors) in order to receive and send the required information over the internet. </p> <Spacer mb={4} /> <Text fontSize={3} fontWeight="bold"> <h2>Contributors to the site</h2> </Text> <Spacer mb={3} /> <p> Contributors to The Great British Public Toilet Map website are asked to sign-in via the Auth0 platform using their email address. This helps us to share data on the quantity and spread of contributions to the site which helps show how the community value the project, to improve our interfaces for our users, to protect our dataset from misuse and to recognise contributions from a user if that user is adding unsuitable content, whether intentionally or inadvertently. </p> <p> A full list of a contributor’s activities will only be accessible to Public Convenience Ltd, for moderating the dataset. A contributor’s full email address will never be disclosed or shared and is only visible to Public Convenience Ltd. </p> <Spacer mb={4} /> <p> If you'd like to know what we've stored about you, or ask us to forget you, or to let us know about something you'd like changed please drop us a line at{' '} <Button as="a" variant="link" href="mailto:gbtoiletmap@gmail.com" target="_blank" rel="noopener noreferrer" > gbtoiletmap@gmail.com </Button> . If you'd like to exercise any of your rights under the GDPR that's the address to use. </p> </Container> </PageLayout> ); }; export default PrivacyPage;
src/components/IntroScreen/index.js
vogelino/design-timeline
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import ReactMarkdown from 'react-markdown'; import ScrollArea from '../ScrollArea'; import { combineCssClasses } from '../../helpers/styleHelper'; import * as introScreenActions from '../../redux/actions/introScreenActions'; import IntroBubbles from './IntroBubbles'; import './IntroScreen.css'; export const IntroScreenComponent = ({ visible, text, title, buttonText, hideIntroScreen, }) => ( <div className={combineCssClasses({ introscreen: true, 'introscreen--visible': visible, 'introscreen--hidden': !visible, })} > <div className="introscreen_content"> <div className="introscreen_start-title">{title}</div> <ScrollArea className="introscreen_start-text"> <ReactMarkdown source={text} /> </ScrollArea> <button className="introscreen_start-button" onClick={hideIntroScreen} > {buttonText} </button> </div> <div className="introscreen_ocean"> <div className="introscreen_wave" /> </div> <IntroBubbles /> </div> ); IntroScreenComponent.defaultProps = { visible: true, title: '', text: '', buttonText: '', hideIntroScreen: (x) => x, }; IntroScreenComponent.propTypes = { visible: PropTypes.bool, title: PropTypes.string, text: PropTypes.string, buttonText: PropTypes.string, hideIntroScreen: PropTypes.func, }; const mapStateToProps = ({ introScreen }) => ({ ...introScreen }); const mapDispatchToProps = (dispatch) => bindActionCreators(introScreenActions, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(IntroScreenComponent);
test/LabelSpec.js
rapilabs/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Label from '../src/Label'; describe('Label', function () { it('Should output a label with message', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> <strong>Message</strong> </Label> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have bsClass by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(React.findDOMNode(instance).className.match(/\blabel\b/)); }); it('Should have bsStyle by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(React.findDOMNode(instance).className.match(/\blabel-default\b/)); }); });
src/svg-icons/notification/phone-paused.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhonePaused = (props) => ( <SvgIcon {...props}> <path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/> </SvgIcon> ); NotificationPhonePaused = pure(NotificationPhonePaused); NotificationPhonePaused.displayName = 'NotificationPhonePaused'; NotificationPhonePaused.muiName = 'SvgIcon'; export default NotificationPhonePaused;
docs/src/main.js
kwangkim/nuclear-js
import React from 'react' import ItemFilterExample from './components/item-filter-example' import addScrollClass from './utils/scroll-class' addScrollClass("scrolled") render(ItemFilterExample, 'item-filter-example') updateSideBar() function render(component, id) { var el = document.getElementById(id) if (el) { React.render(React.createElement(component), el) } } function updateSideBar() { var sideBarElements = document.getElementsByClassName('sidebar-links--item') for (var i in sideBarElements) { if (sideBarElements[i].firstChild) { if (window.location.href === sideBarElements[i].firstChild.href) { sideBarElements[i].className = 'sidebar-links--item-active' } else { sideBarElements[i].className = 'sidebar-links--item' } } } }
src/App.js
stevecd/mpcnc_calc_react
import React, { Component } from 'react'; import update from 'react-addons-update'; import {Navbar, Tabs, Tab, Input, Grid, Row, Col, Button } from 'react-bootstrap'; import 'bootstrap/dist/css/bootstrap.css'; import './App.css'; let defaultState = { x: 21, y: 21, z: 6.1, xCa: 11, yCa: 11, zCa: 7.9, xBa: 7, yBa: 7, units: "Inches" } export default class App extends Component { constructor(props) { super(props) const { query } = this.props.location defaultState = update(defaultState, { $merge: query }) this.state = defaultState } handleXChange = (e) => { const newState = update(this.state, { x: {$set: e.target.value} }) this.setState(newState) } handleYChange = (e) => { const newState = update(this.state, { y: {$set: e.target.value} }) this.setState(newState) } handleZChange = (e) => { const newState = update(this.state, { z: {$set: e.target.value} }) this.setState(newState) } handleResetToDefaults = (e) => { const newState = defaultState this.setState(newState) } handleXAdditionChange = (e) => { const newState = update(this.state, { xCa: {$set: e.target.value} }) this.setState(newState) } handleYAdditionChange = (e) => { const newState = update(this.state, {yCa: {$set: e.target.value}}) this.setState(newState) } handleZAdditionChange = (e) => { const newState = update(this.state, {zCa: {$set: e.target.value}}) this.setState(newState) } handleXBeltAdditionChange = (e) => { const newState = update(this.state, {xBa: {$set: e.target.value}}) this.setState(newState) } handleYBeltAdditionChange = (e) => { const newState = update(this.state, {yBa: {$set: e.target.value}}) this.setState(newState) } handleUnitsChange = (e) => { if(this.state.units == "Centimeters" && e.target.value == "Inches"){ let convertedValues = {} for(let key in this.state) { if(!isNaN(this.state[key])) { convertedValues[key] = this.state[key] / 2.54 } } convertedValues.units = "Inches" this.setState(convertedValues) } else if(this.state.units == "Inches" && e.target.value == "Centimeters") { let convertedValues = {} for(let key in this.state) { if(!isNaN(this.state[key])) { convertedValues[key] = this.state[key] * 2.54 } } convertedValues.units = "Centimeters" this.setState(convertedValues) } } // http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object serialize(obj) { let str = []; for(let p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } calculateValues = () => { let result = { xConduitLength: parseFloat(this.state.x) + parseFloat(this.state.xCa), yConduitLength: parseFloat(this.state.y) + parseFloat(this.state.yCa), zConduitLength: parseFloat(this.state.z) + parseFloat(this.state.zCa), } result.zThreadedRod = result.zConduitLength - 2 result.xBelt = result.xConduitLength + parseFloat(this.state.xBa), result.yBelt = result.yConduitLength + parseFloat(this.state.yBa), result.totalXConduit = result.xConduitLength * 3 result.totalYConduit = result.yConduitLength * 3 result.totalZConduit = result.zConduitLength * 2 result.totalConduit = result.totalXConduit + result.totalYConduit + result.totalZConduit result.totalXBelt = result.xBelt * 2 result.totalYBelt = result.yBelt * 2 result.totalBelt = result.totalXBelt + result.totalYBelt for(let key in result) { if(isNaN(result[key])) { result[key] = NaN } else { result[key] = parseFloat(result[key]).toFixed(1) } } result.link = new RegExp(/^.*\//).exec(window.location.href) + "?" + this.serialize(this.state) return result } render() { const calculatedValues = this.calculateValues() return ( <Grid> <Navbar fixedTop> <Navbar.Header> <Navbar.Brand> Simple MPCNC Calc </Navbar.Brand> </Navbar.Header> </Navbar> <Row> <Tabs defaultActiveKey={1} animation={false}> <br/> <Tab eventKey={1} title="Calc"> <Row> <Col xs={4} md={4}> <form className="form-horizontal"> <fieldset> <legend>Desired Cutting Area</legend> <Input type="number" step="0.1" placeholder="X Dimension" value={this.state.x} onChange={this.handleXChange} label="X:" labelClassName="col-xs-2" wrapperClassName="col-xs-10" /> <Input type="number" step="0.1" placeholder="Y Dimension" value={this.state.y} onChange={this.handleYChange} label="Y:" labelClassName="col-xs-2" wrapperClassName="col-xs-10" /> <Input type="number" step="0.1" placeholder="Z Dimension" value={this.state.z} onChange={this.handleZChange} label="Z:" labelClassName="col-xs-2" wrapperClassName="col-xs-10" /> <Input type="select" label="Units:" labelClassName="col-xs-2" wrapperClassName="col-xs-8 col-xs-offset-2" onChange={this.handleUnitsChange} value={this.state.units} > <option value="Inches">Inches</option> <option value="Centimeters">Centimeters</option> </Input> <Button className="pull-right" onClick={this.handleResetToDefaults} >Reset To Defaults</Button><br /><br /> <Input type="textarea" placeholder="Link to this config" label="Link:" value={calculatedValues.link} rows={4} readOnly /> </fieldset> </form> </Col> <Col xs={4} md={4}> <form className="form-horizontal"> <fieldset> <legend>Piece Lengths</legend> <Input type="text" label="X Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.xConduitLength} addonAfter="x 3" readOnly /> <Input type="text" label="Y Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.yConduitLength} addonAfter="x 3" readOnly /> <Input type="text" label="Z Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.zConduitLength} addonAfter="x 2" readOnly /> <hr/> <Input type="text" label="Z Rod" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.zThreadedRod} addonAfter="x 1" readOnly /> <hr /> <Input type="text" label="X Belt" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.xBelt} addonAfter="x 2" readOnly /> <Input type="text" label="Y Belt" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.yBelt} addonAfter="x 2" readOnly /> </fieldset> </form> </Col> <Col xs={4} md={4}> <form className="form-horizontal"> <fieldset> <legend>Total Lengths</legend> <Input type="text" label="X Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalXConduit} readOnly /> <Input type="text" label="Y Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalYConduit} readOnly /> <Input type="text" label="Z Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalZConduit} readOnly /> <Input type="text" label="Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalConduit} readOnly /> <hr/> <Input type="text" label="X Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalXBelt} readOnly /> <Input type="text" label="Y Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalYBelt} readOnly /> <Input type="text" label="Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalBelt} readOnly /> </fieldset> </form> </Col> </Row> <Row> <form className="form-horizontal"> <fieldset> <legend>Settings</legend> <Col xs={6}> <Input type="number" step="0.1" label="Added to X Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.xCa} onChange={this.handleXAdditionChange}/> <Input type="number" step="0.1" label="Added to Y Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.yCa} onChange={this.handleYAdditionChange}/> <Input type="number" step="0.1" label="Added to Z Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.zCa} onChange={this.handleZAdditionChange}/> </Col> <Col xs={6}> <Input type="number" step="0.1" label="Added to X Belts" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.xBa} onChange={this.handleXBeltAdditionChange}/> <Input type="number" step="0.1" label="Added to Y Belts" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.yBa} onChange={this.handleYBeltAdditionChange}/> </Col> </fieldset> </form> </Row> </Tab> <Tab eventKey={3} title="About"> <Row> <ul> <li> Values for default settings ( <a href="http://stevecd.github.io/mpcnc_calc_react/">http://stevecd.github.io/mpcnc_calc_react/</a> ) come from these <a href="http://public.vicious1.de/Assembly_Instructions_v0.2.pdf">Detailed Assembly Instructions</a> by <a href="http://www.vicious1.com/forums/users/bofferle/">Bofferle</a> . </li> <li> I made this app while following along with the React.js <a href="https://facebook.github.io/react/docs/getting-started.html">getting started tutorial.</a> </li> <li> It is a simple take on the <a href="http://www.thingiverse.com/thing:948320">Mostly Printed CNC / Multitool Layout Size Calculator</a> by <a href="http://www.thingiverse.com/GeoDave/about">GeoDave</a>. </li> <li> repo at <a href="https://github.com/stevecd/mpcnc_calc_react">https://github.com/stevecd/mpcnc_calc_react</a> </li> </ul> </Row> </Tab> </Tabs> </Row> </Grid> ); } }
packages/reactor-kitchensink/src/examples/DragAndDrop/Proxies/Proxies.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Panel } from '@extjs/ext-react'; import './styles.css'; Ext.require(['Ext.drag.*']); export default class Proxies extends Component { state = { noneText: 'No Proxy' } render() { const {noneText} = this.state; return ( <Panel ref="mainPanel" padding={5} shadow > <div ref="none" className="proxy-none proxy-source">{noneText}</div> <div ref="original" className="proxy-original proxy-source">Element as proxy with revert: true</div> <div ref="placeholder" className="proxy-placeholder proxy-source">Placeholder</div> </Panel> ) } componentDidMount() { this.sources = [ // No proxy, just track the mouse cursor new Ext.drag.Source({ element: this.refs.none, constrain: this.refs.mainPanel.el, proxy: 'none', listeners: { dragmove: (source, info) => { const pos = info.proxy.current, noneText = Ext.String.format('X: {0}, Y: {1}', Math.round(pos.x), Math.round(pos.y)); this.setState({ noneText }); }, dragend: () => { this.setState({ noneText: 'No Proxy' }); } } }), // Use the drag element as the proxy. Animate it back into position on drop. new Ext.drag.Source({ element: this.refs.original, revert: true, constrain: this.refs.mainPanel.el, proxy: 'original' }), // Leave the drag element in place and create a custom placeholder. new Ext.drag.Source({ element: this.refs.placeholder, constrain: this.refs.mainPanel.el, proxy: { type: 'placeholder', cls: 'proxy-drag-custom', html: 'Custom' } }) ]; } componentWillUnmount() { this.sources.forEach(Ext.destroy.bind(Ext)); } }
src/components/searchBar.js
gabriellisboa/reduxStudies
import React, { Component } from 'react'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; } onInputChange(event) { this.setState({ term: event.target.value, }); } render() { return ( <div className="search-bar"> <input value={this.state.term} onChange={(event) => this.onInputChange(event.target.value)} /> </div> ); } onInputChange(term) { this.setState({ term }); this.props.onSearchTermChange(term); } }; export default SearchBar;
src/svg-icons/action/stars.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionStars = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z"/> </SvgIcon> ); ActionStars = pure(ActionStars); ActionStars.displayName = 'ActionStars'; ActionStars.muiName = 'SvgIcon'; export default ActionStars;
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js
Jaeandroid/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import classNames from 'classnames'; import DialogStore from 'stores/DialogStore'; export default React.createClass({ mixins: [PureRenderMixin], getInitialState() { return { typing: null, show: false }; }, componentDidMount() { DialogStore.addTypingListener(this.onTypingChange); }, componentWillUnmount() { DialogStore.removeTypingListener(this.onTypingChange); }, onTypingChange() { const typing = DialogStore.getSelectedDialogTyping(); if (typing === null) { this.setState({show: false}); } else { this.setState({typing: typing, show: true}); } }, render() { const typing = this.state.typing; const show = this.state.show; const typingClassName = classNames('typing', { 'typing--hidden': show === false }); return ( <div className={typingClassName}> <div className="typing-indicator"><i></i><i></i><i></i></div> <span>{typing}</span> </div> ); } });
src/app/js/index.js
AppSaloon/socket.io-tester
import { Provider } from 'react-redux' import { createStore } from 'redux' import React from 'react' import { render } from 'react-dom' import reducer from './reducers/reducer' import App from './components/App' const store = createStore(reducer, window.devToolsExtension ? window.devToolsExtension() : undefined ); export { store } render( <Provider store={store}> <App/> </Provider>, document.getElementById('app') )