path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
node_modules/semantic-ui-react/src/elements/List/ListList.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, } from '../../lib' /** * A list can contain a sub list. */ function ListList(props) { const { children, className } = props const rest = getUnhandledProps(ListList, props) const ElementType = getElementType(ListList, props) const classes = cx( useKeyOnly(ElementType !== 'ul' && ElementType !== 'ol', 'list'), className, ) return <ElementType {...rest} className={classes}>{children}</ElementType> } ListList._meta = { name: 'ListList', parent: 'List', type: META.TYPES.ELEMENT, } ListList.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, } export default ListList
examples/with-sentry-simple/pages/client/test1.js
BlancheXu/test
import React from 'react' const Test1 = () => <h1>Client Test 1</h1> Test1.getInitialProps = () => { throw new Error('Client Test 1') } export default Test1
src/containers/Home/target/Target.js
UncleYee/crm-ui
import React from 'react'; import {WhitePanel, CircleProgress, LineProgress} from 'components'; import {primaryColor} from 'utils/colors'; const styles = { root: { marginRight: 10, width: 900, height: 180 }, circle: { marginLeft: 28 }, lists: { display: 'inline-block', width: 700, padding: '12px 40px', verticalAlign: 'top' }, item: { margin: '5px 0' } }; export default class Target extends React.Component { static propTypes = { name: React.PropTypes.string }; constructor(props) { super(props); } render() { return ( <WhitePanel style={styles.root} title="我的销售目标"> <CircleProgress style={styles.circle} title="完成率" percent={30}/> <div style={styles.lists}> <LineProgress style={styles.item} strokeColor={primaryColor} percent={100} title="销售目标" value="46,110.00"/> <LineProgress style={styles.item} strokeColor="#c78ff2" percent={80} title="本月预测" value="28,110.00"/> <LineProgress style={styles.item} strokeColor="#ffda54" percent={30} title="已完成" value="8,110.00"/> </div> </WhitePanel> ); } }
blueocean-material-icons/src/js/components/svg-icons/maps/local-airport.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsLocalAirport = (props) => ( <SvgIcon {...props}> <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/> </SvgIcon> ); MapsLocalAirport.displayName = 'MapsLocalAirport'; MapsLocalAirport.muiName = 'SvgIcon'; export default MapsLocalAirport;
examples/with-reason-relay/pages/_app.js
JeromeFitz/next.js
import React from 'react' import App from 'next/app' const isStatusCodeOk = (res) => { try { return `${res.statusCode}`.startsWith('2') } catch (e) { return true } } class MyApp extends App { static async getInitialProps({ Component, ctx }) { let pageProps = {} if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { pageProps, path: ctx.asPath, isOk: isStatusCodeOk(ctx.res), } } render() { const { Component, pageProps, isOk } = this.props return isOk ? ( <div> <Component {...pageProps[0]} /> </div> ) : ( /* ⚠️ Important to only render these components when statusCode is NOT ok */ <Component {...pageProps[0]} /> ) } } export default MyApp
benchmarks/dom-comparison/src/implementations/aphrodite/Box.js
risetechnologies/fela
/* eslint-disable react/prop-types */ import React from 'react'; import View from './View'; import { StyleSheet } from 'aphrodite'; const Box = ({ color, fixed = false, layout = 'column', outer = false, ...other }) => ( <View {...other} style={[ styles[`color${color}`], fixed && styles.fixed, layout === 'row' && styles.row, outer && styles.outer ]} /> ); const styles = StyleSheet.create({ outer: { alignSelf: 'flex-start', padding: 4 }, row: { flexDirection: 'row' }, color0: { backgroundColor: '#14171A' }, color1: { backgroundColor: '#AAB8C2' }, color2: { backgroundColor: '#E6ECF0' }, color3: { backgroundColor: '#FFAD1F' }, color4: { backgroundColor: '#F45D22' }, color5: { backgroundColor: '#E0245E' }, fixed: { width: 6, height: 6 } }); export default Box;
app/javascript/mastodon/features/home_timeline/components/column_settings.js
dunn/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { settings, onChange } = this.props; return ( <div> <span className='column-settings__section'><FormattedMessage id='home.column_settings.basic' defaultMessage='Basic' /></span> <div className='column-settings__row'> <SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_reblogs' defaultMessage='Show boosts' />} /> </div> <div className='column-settings__row'> <SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reply']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_replies' defaultMessage='Show replies' />} /> </div> </div> ); } }
src/Parser/Druid/Restoration/Modules/Traits/RelicTraits.js
enragednuke/WoWAnalyzer
import React from 'react'; import StatisticsListBox, { STATISTIC_ORDER } from 'Main/StatisticsListBox'; import Analyzer from 'Parser/Core/Analyzer'; import ArmorOfTheAncients from './ArmorOfTheAncients'; import BlessingOfTheWorldTree from './BlessingOfTheWorldTree'; import EssenceOfNordrassil from './EssenceOfNordrassil'; import Grovewalker from './Grovewalker'; import InfusionOfNature from './InfusionOfNature'; import KnowledgeOfTheAncients from './KnowledgeOfTheAncients'; import NaturalMending from './NaturalMending'; import Persistence from './Persistence'; import SeedsOfTheWorldTree from './SeedsOfTheWorldTree'; import EternalRestoration from './EternalRestoration'; class RelicTraits extends Analyzer { static dependencies = { armorOfTheAncients: ArmorOfTheAncients, blessingOfTheWorldTree: BlessingOfTheWorldTree, essenceOfNordrassil: EssenceOfNordrassil, grovewalker: Grovewalker, infusionOfNature: InfusionOfNature, knowledgeOfTheAncients: KnowledgeOfTheAncients, naturalMending: NaturalMending, persistence: Persistence, seedsOfTheWorldTree: SeedsOfTheWorldTree, eternalRestoration: EternalRestoration, }; statistic() { return ( <StatisticsListBox title="Relic traits" tooltip="This only calculates the value of the last point of each relic trait; for you with your gear and only during this fight. The value of an additional point would likely be slightly lower due to increased overhealing." style={{ minHeight: 186 }} > {this.blessingOfTheWorldTree.subStatistic()} {this.essenceOfNordrassil.subStatistic()} {this.grovewalker.subStatistic()} {this.infusionOfNature.subStatistic()} {this.knowledgeOfTheAncients.subStatistic()} {this.naturalMending.subStatistic()} {this.persistence.subStatistic()} {this.seedsOfTheWorldTree.subStatistic()} {this.eternalRestoration.subStatistic()} </StatisticsListBox> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(0); } export default RelicTraits;
src/Home/Stats.js
Software-Eng-THU-2015/pacific-rim
import React, { Component } from 'react'; export default class Stats extends Component { render() { return ( <div> <div className = "col-xs-12 label label-primary" style={{"padding":"10px 10px 10px 10px"}}> <h1> 900 Miles </h1> </div> <div className = "col-xs-6 label label-info" style={{"padding":"10px 10px 10px 10px"}}> <h2>10017 Steps</h2> </div> <div className = "col-xs-6 label label-info" style={{"padding":"10px 10px 10px 10px"}}> <h2>600k Calorie</h2> </div> </div> ); } }
imports/ui/components/holidays-list.js
gagpmr/app-met
import React from 'react'; import { Loading } from './loading.js'; import { Pagination } from 'react-bootstrap'; import { removeHoliday } from '/imports/api/holidays/methods.js'; export const HolidaysList = React.createClass({ getInitialState() { return { activePage: 1, range: 15 }; }, remove(id, e) { e.preventDefault(); removeHoliday.call({ _id: id }, (error) => { if (error) { Bert.alert(error, 'danger'); } else { Bert.alert('Holiday Removed!', 'success'); } }); }, handleSelect(eventKey) { this.setState({ activePage: eventKey, range: 15 }); }, propTypes: { loading: React.PropTypes.bool, holidays: React.PropTypes.array }, pagesNo(arrayLength) { return Math.ceil(arrayLength / this.state.range); }, render() { if (this.props.loading) { return <div className="middle"> <Loading/> </div> } else { var rows = []; if (this.props.holidays.length > 0) { var startIndex = (this.state.activePage * this.state.range) - this.state.range; for (var index = 0; index < this.state.range; index++) { var element = this.props.holidays[startIndex]; if (element !== undefined) { rows.push( <tr key={ element._id }> <th className="text-center font-bolder"> { element.StringValue } </th> <td className="text-center font-bolder"> <a href="" onClick={ this.remove.bind(this, element._id) }>Delete</a> </td> </tr> ); } startIndex++; } } return ( <span> <div className="col-md-6 col-md-offset-3"> <table className="table table-bordered table-condensed table-striped"> <thead> <tr> <th colSpan="6" className="text-center h4 font-bolder"> Holidays &nbsp; <a href="/add-holiday"> <i className="fa fa-plus" aria-hidden="true"></i> </a> &nbsp; <a href="/"> <i className="fa fa-home" aria-hidden="true"></i> </a> </th> </tr> </thead> <tbody> { rows } </tbody> </table> </div> <div className="hPagination"> <Pagination prev next first last ellipsis boundaryLinks items={ this.pagesNo(this.props.holidays.length) } maxButtons={ 9 } activePage={ this.state.activePage } onSelect={ this.handleSelect }/> </div> </span> ); } } });
src/containers/SettingsPageContainer.js
alistairmgreen/soaring-analyst
import React from 'react'; import SettingsPage from '../components/pages/SettingsPage'; export default function SettingsPageContainer() { return ( <SettingsPage /> ); }
src/components/pages/Home/sections/ExpeditionSection/index.js
humaniq/humaniq-pwa-website
import React from 'react' import A_Title_H from 'A_Title_H' import A_Btn_H from 'A_Btn_H' import SectionCounter from '../common/SectionCounter/index.js' import InfoColumns from '../common/InfoColumns' import './styles.scss' import { cssClassName } from 'utils' const cn = cssClassName('SE_Home_Expedition') const SE_Home_Expedition = ({ mix }) => ( <section className={cn([mix])}> <div className={cn('content')}> <A_Title_H mix={cn('title')} type="section" theme="dark"> Humaniq expedition: the first<br /> step in financial inclusion </A_Title_H> <InfoColumns mix={cn('info-columns')} columns={infoColumns} type="narrow" /> <div className={cn('button')}> <A_Btn_H to="http://humaniqchallenge.com">About expedition</A_Btn_H> </div> </div> <SectionCounter sectionNum={11} theme="bright" /> </section> ) export default SE_Home_Expedition const infoColumns = [ { title: 'Startup contest', text: 'In order to bring together a network of like-minded individuals and then choose 10 projects for entry into the Humaniq system, we are launching the Humaniq Global Challenge for entrepreneurs, developers, marketing specialists and economists.', }, { title: 'Benefits', text: '10 Finalists will receive expert advice from top consultants in their field, as well as the chance to gain investment and to enter the Humaniq accelerator.', }, { title: 'Trip to Kenya', text: 'The three best teams will go on a trip to Kenya to learn more about the lives of the unbanked and put the finishing touches to their projects ahead of an ICO, which will be supported by Humaniq.', }, ]
examples/01 Dustbin/Multiple Targets/Container.js
nagaozen/react-dnd
import React, { Component } from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend, { NativeTypes } from 'react-dnd/modules/backends/HTML5'; import Dustbin from './Dustbin'; import Box from './Box'; import ItemTypes from './ItemTypes'; import update from 'react/lib/update'; @DragDropContext(HTML5Backend) export default class Container extends Component { constructor(props) { super(props); this.state = { dustbins: [ { accepts: [ItemTypes.GLASS], lastDroppedItem: null }, { accepts: [ItemTypes.FOOD], lastDroppedItem: null }, { accepts: [ItemTypes.PAPER, ItemTypes.GLASS, NativeTypes.URL], lastDroppedItem: null }, { accepts: [ItemTypes.PAPER, NativeTypes.FILE], lastDroppedItem: null } ], boxes: [ { name: 'Bottle', type: ItemTypes.GLASS }, { name: 'Banana', type: ItemTypes.FOOD }, { name: 'Magazine', type: ItemTypes.PAPER } ], droppedBoxNames: [] }; } isDropped(boxName) { return this.state.droppedBoxNames.indexOf(boxName) > -1; } render() { const { boxes, dustbins } = this.state; return ( <div> <div style={{ overflow: 'hidden', clear: 'both' }}> {dustbins.map(({ accepts, lastDroppedItem }, index) => <Dustbin accepts={accepts} lastDroppedItem={lastDroppedItem} onDrop={(item) => this.handleDrop(index, item)} key={index} /> )} </div> <div style={{ overflow: 'hidden', clear: 'both' }}> {boxes.map(({ name, type }, index) => <Box name={name} type={type} isDropped={this.isDropped(name)} key={index} /> )} </div> </div> ); } handleDrop(index, item) { const { name } = item; this.setState(update(this.state, { dustbins: { [index]: { lastDroppedItem: { $set: item } } }, droppedBoxNames: name ? { $push: [name] } : {} })); } }
app/javascript/components/provider-dashboard-charts/servers-pie-chart/serversAvailablePieChart.js
ManageIQ/manageiq-ui-classic
import React from 'react'; import PropTypes from 'prop-types'; import { PieChart } from '@carbon/charts-react'; import EmptyChart from '../emptyChart'; const ServersAvailablePieChart = ({ data, config }) => { const pieChartData = [ { group: config.usageDataName, value: data.data.columns.used, }, { group: config.availableDataName, value: data.data.columns.available, }, ]; const PieOptions = { height: '230px', resizable: true, tooltip: { truncation: { type: 'none', }, }, legend: { enabled: true, alignment: 'right', }, }; return ( <div> <div className="utilization-trend-chart-pf"> <h3>{config.title}</h3> <div className="current-values" /> </div> {data.dataAvailable ? <PieChart data={pieChartData} options={PieOptions} /> : <EmptyChart />} <span className="trend-footer-pf">{config.legendLeftText}</span> </div> ); }; ServersAvailablePieChart.propTypes = { data: PropTypes.objectOf(PropTypes.any).isRequired, config: PropTypes.shape({ availableDataName: PropTypes.string.isRequired, legendLeftText: PropTypes.string.isRequired, usageDataName: PropTypes.string.isRequired, title: PropTypes.string.isRequired, units: PropTypes.string.isRequired, }).isRequired, }; export default ServersAvailablePieChart;
app/jsx/shared/SpaceTile/index.js
sfu/canvas-spaces
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import SpaceTile_Information from './SpaceTile_Information'; import SpaceTile_Avatar from './SpaceTile_Avatar'; import SpaceSettingsModal from '../SpaceSettingsModal'; class SpaceTile extends Component { constructor(props) { super(props); this.state = { modalIsOpen: false, }; this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); } openModal(e) { e.preventDefault(); this.setState({ modalIsOpen: true, }); } closeModal() { this.setState({ modalIsOpen: false, }); } render() { const serverConfig = window.ENV.CANVAS_SPACES_CONFIG || {}; const space_url = `/groups/${this.props.space.id}`; const space = this.props.space; return ( <div> <div className="SpaceTile"> <SpaceTile_Information name={space.name} description={space.description} is_leader={space.is_leader} editButtonHandler={this.openModal} space_url={space_url} /> <SpaceTile_Avatar avatar={this.props.avatar} /> </div> <SpaceSettingsModal space={this.props.space} className="ReactModal__Content--canvas" overlayClassName="ReactModal__Overlay--canvas" modalIsOpen={this.state.modalIsOpen} onRequestClose={this.closeModal} serverConfig={serverConfig} contentLabel={space.name} updateSpace={this.props.updateSpace} deleteSpace={this.props.deleteSpace} /> </div> ); } } SpaceTile.propTypes = { space: PropTypes.object.isRequired, avatar: PropTypes.string, context: PropTypes.string.isRequired, updateSpace: PropTypes.func.isRequired, deleteSpace: PropTypes.func.isRequired, }; export default SpaceTile;
stories/radio/index.js
lanyuechen/dh-component
import React from 'react'; import { Radio } from '../../src'; import { storiesOf, action, linkTo } from '@kadira/storybook'; const options = { inline: true } storiesOf('单选框', module) .addWithInfo( '单选框1', () => ( <Radio.Group defaultSelectKey="b" onChange={(key) => console.log('select =', key)}> <Radio key="a">选项1</Radio> <Radio key="b">选项2</Radio> <Radio key="c">选项3</Radio> <Radio key="d">选项4</Radio> </Radio.Group> ), options) .addWithInfo( '单选框2', () => ( <div> <Radio key="a" checked onChange={(key) => console.log('select =', key)}>选项1(checked=true)</Radio> <Radio key="b" checked={false}>选项2(checked=false)</Radio> <Radio key="c" onChange={(key) => console.log('select =', key)}>选项3</Radio> <Radio key="d">选项4</Radio> </div> ), options);
ui/src/main/js/components/UpdateStatus.js
crashlytics/aurora
import React from 'react'; import UpdateTime from 'components/UpdateTime'; import { UPDATE_STATUS } from 'utils/Thrift'; import { isInProgressUpdate } from 'utils/Update'; export default function UpdateStatus({ update }) { const time = isInProgressUpdate(update) ? '' : <UpdateTime update={update} />; return (<div> <div className='update-byline'> <span> Update started by <strong>{update.update.summary.user}</strong> </span> <span>&bull;</span> <span> Status: <strong>{UPDATE_STATUS[update.update.summary.state.status]}</strong> </span> </div> {time} </div>); }
index.ios.js
calvinchengcc/busnapper
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ "use strict"; import React, { Component } from 'react'; import { Alert, AppRegistry, Button, Navigator, StyleSheet, Text, TouchableHighlight, TouchableOpacity, Vibration, View } from 'react-native'; import MapView from 'react-native-maps'; var {GooglePlacesAutocomplete} = require('react-native-google-places-autocomplete'); //navigation const nav_routes = [ {title: 'Map', index: 0}, {title: 'Address', index: 1}, {title: 'BusDetails', index: 2}, ]; export default class busnapper extends Component { constructor(props) { super(props); this.state = { isDestinationSet: false, initialPosition: { latitude: 49.264, longitude: -123.19, latitudeDelta: 0.02, longitudeDelta: 0.02 }, lastPosition: { latitude: 49.264, longitude: -123.19 }, region: { latitude: 49.264, longitude: -123.19, latitudeDelta: 0.02, longitudeDelta: 0.02 }, destMarker: { coordinate: { latitude: 0, longitude: 0 }, loaded: false }, busStopMarkers: [], selectedRoute: null, destination: null }; this.watchID = null; } componentWillMount() { navigator.geolocation.getCurrentPosition( (position) => { let lat = position.coords.latitude; let lon = position.coords.longitude; this.fetchStopData(lat, lon); this.state.initialPosition = { latitude: lat, longitude: lon, latitudeDelta: 0.02, longitudeDelta: 0.02 }; this.state.region = this.state.initialPosition; console.log("init lat: " + this.state.region.latitude + ", long: " + this.state.region.longitude); }, (error) => alert(JSON.stringify(error)), ); this.watchID = navigator.geolocation.watchPosition( (position) => { // console.log("watch position triggered"); //console.log("destination (from watch) - lat: " + this.state.destination.latitude + ", long: " + this.state.destination.longitude); this.setState({lastPosition: { latitude: position.coords.latitude, longitude: position.coords.longitude }}, () => { //console.log("watch position triggered"); console.log("last lat: " + this.state.lastPosition.latitude + ", long: " + this.state.lastPosition.longitude); if (this.state.destination !== null) { let distance = getDistanceKmBetween( this.state.lastPosition, this.state.destination); console.log(`Distance to dest: ${distance} km`); if (distance < 1) { console.log("Vibrating!!!"); alert("Wake up!"); Vibration.vibrate(); } } }); }, (error) => alert(JSON.stringify(error)), {enableHighAccuracy: true} ); } fetchStopData() { //console.log("fetching data from lat: " + latitude + ", long: " + longitude); //console.log("while region at lat: " + this.state.region.latitude + ", long: " + this.state.region.longitude); let stopQuery = (this.state.selectedRoute === null) ? '' : `stopNo=${this.state.selectedRoute}`; let requestUrl = `https://api.translink.ca/RTTIAPI/V1/stops` + `?apiKey=rQef46wC3btmRlRln1gi&radius=2000` + `&lat=${this.state.region.latitude.toFixed(6)}&long=${this.state.region.longitude.toFixed(6)}${stopQuery}`; let response = fetch(requestUrl, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }}).then((response) => { response.json().then((responseStops) => { if (typeof responseStops.map !== 'function') { //console.warn(`No stops found for (${latitude}, ${longitude}.`); return; } let stops = responseStops.map((responseStop) => { return { stopNum: responseStop.StopNo, name: responseStop.Name, routes: responseStop.Routes, coordinate: { latitude: responseStop.Latitude, longitude: responseStop.Longitude } }; }); this.setState({busStopMarkers: stops}); }).catch((error) => { console.error(error); }) }).catch((error) => { console.error(error); }); } componentWillUnmount() { navigator.geolocation.clearWatch(this.watchID); } onButtonPressed(data, details = null) { let address = data.description; var API = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyC4zC0FQBYsOf8E50t00kmC8lzW7nPUn8s"; let response = fetch(API, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }}).then((response) => { response.json().then((geocode) => { let lat = geocode.results[0].geometry.location.lat; let long = geocode.results[0].geometry.location.lng; this.setState({region: {latitude: lat, longitude: long, latitudeDelta: 0.02, longitudeDelta:0.02}}); this.setState({isDestinationSet: false}); //about to set a new destination! }).catch((error) => { console.error(error); }) }).catch((error) => { console.error(error); }); } onRegionChangeComplete(region) { this.setState({region}); if(this.state.isDestinationSet==false) { this.fetchStopData(); //ISSUE FIX: this.fetchStopData(region.latitude, region.longitude) -> region.latitude and region.longitude values were incorrect, console.log("fetching data while isDestinationSet is " + this.state.isDestinationSet); } console.log("changed to lat: " + this.state.region.latitude + ", long: " + this.state.region.longitude); } render() { return ( //view controller <Navigator initialRoute={nav_routes[0]} initialRouteStack = {nav_routes} renderScene = {(route, navigator) => { if(route.index==1) { //Secondary view - map return ( <View style = {styles.parent}> <View style={styles.fullscreen}> <MapView style={{flex:0.75}} initialRegion={{ latitude: this.state.destMarker.coordinate.latitude, longitude: this.state.destMarker.coordinate.longitude, latitudeDelta: 0.02, longitudeDelta: 0.02, }} region = {this.state.region} loadingEnabled={true} ref = {ref => {this.map = ref; }} showsUserLocation = {true} scrollEnabled = {true} onRegionChangeComplete = { this.onRegionChangeComplete.bind(this) } > {this.state.busStopMarkers.map(busStopMarker => ( <MapView.Marker key={busStopMarker.stopNum} identifier={JSON.stringify(busStopMarker.stopNum)} title = {busStopMarker.name} coordinate={busStopMarker.coordinate} > <MapView.Callout> <TouchableOpacity onPress = { () => { Alert.alert( busStopMarker.name, `Do you want to set your destination as ` + `${busStopMarker.name} [${busStopMarker.routes}]?`, [ {text: 'Nope.', onPress: () => console.log('Cancel pressed')}, {text: 'Yes, let me nap!', onPress: () => { console.log('OK Pressed'); this.setState({destination: busStopMarker.coordinate}); var busStopMarkers = []; busStopMarkers.push(busStopMarker); this.setState({busStopMarkers}); this.setState({isDestinationSet: true}); var coords = []; coords.push(this.state.lastPosition); coords.push(busStopMarker.coordinate); this.map.fitToCoordinates(coords, {edgePadding: {top: 50, right: 50, bottom: 50, left: 50}, animated: false}); }} ] ); }} > <Text> {busStopMarker.name} </Text> </TouchableOpacity> </MapView.Callout> </MapView.Marker> ))} <MapView.Marker coordinate = {this.state.destMarker.coordinate} pinColor = "blue" /> </MapView> </View> <View style = {[{bottom: 10}, styles.overlay]}> <Button onPress={() => {navigator.pop()}} //return to index 0 (search page) title="Destination Address" /> </View> <View style = {[{bottom: 60}, styles.overlay]}> <Button onPress={() => {navigator.push(nav_routes[2])}} //go to index 2 (not implemented yet) title="Bus Route" /> </View> </View> ); } else if(route.index==0) { //main view - search page return ( <GooglePlacesAutocomplete placeholder='Enter Destination' minLength={2} // minimum length of text to search autoFocus={false} listViewDisplayed='true' // true/false/undefined fetchDetails={true} renderDescription={(row) => row.description} // custom description render onPress={ (data, details=null) => { this.onButtonPressed(data, details); navigator.push(nav_routes[1]); }} getDefaultValue={() => { return ''; // text input default value }} query={{ // available options: https://developers.google.com/places/web-service/autocomplete key: 'AIzaSyCr1YQ52b_kW7IDE-5e5rEtjuSOuaB8zqA', language: 'en', // language of the results components: 'country:ca' //limit searches to Canada }} styles={{ description: { fontWeight: 'bold', }, predefinedPlacesDescription: { color: '#1faadb', }, }} nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch GoogleReverseGeocodingQuery={{ // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro }} GooglePlacesSearchQuery={{ // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search rankby: 'distance', }} debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 200ms. /> ); } else if(route.index==2) { //Third view; not implemented } }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, fullscreen: { flex:1 }, parent: { flex:1 }, overlay: { right: 10, position: 'absolute', backgroundColor: "white", opacity: 0.8, borderRadius: 20, overflow: 'hidden' } }); AppRegistry.registerComponent('busnapper', () => busnapper); function getDistanceKmBetween(coord1, coord2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(coord1.latitude - coord2.latitude); var dLon = deg2rad(coord1.longitude - coord2.longitude); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(coord1.latitude)) * Math.cos(deg2rad(coord2.latitude)) * Math.sin(dLon/2) * Math.sin(dLon/2); return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); } function deg2rad(deg) { return deg * (Math.PI/180) }
es/components/HeaderBar/Volume.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose"; import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import IconButton from "@material-ui/core/es/IconButton"; import VolumeDownIcon from "@material-ui/icons/es/VolumeDown"; import VolumeMuteIcon from "@material-ui/icons/es/VolumeMute"; import VolumeOffIcon from "@material-ui/icons/es/VolumeOff"; import VolumeUpIcon from "@material-ui/icons/es/VolumeUp"; import Slider from '@material-ui/lab/Slider'; var Volume = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Volume, _React$Component); function Volume() { var _temp, _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.handleVolumeChange = function (e, volume) { _this.props.onVolumeChange(volume); }, _this.handleMuteClick = function () { if (_this.props.muted) { _this.props.onUnmute(); } else { _this.props.onMute(); } }, _temp) || _assertThisInitialized(_this); } var _proto = Volume.prototype; _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return this.props.volume !== nextProps.volume || this.props.muted !== nextProps.muted; }; _proto.render = function render() { var VolumeIcon = VolumeUpIcon; if (this.props.muted) { VolumeIcon = VolumeOffIcon; } else if (this.props.volume === 0) { VolumeIcon = VolumeMuteIcon; } else if (this.props.volume < 50) { VolumeIcon = VolumeDownIcon; } return _jsx("div", { className: cx('VolumeSlider', this.props.className) }, void 0, _jsx(IconButton, { onClick: this.handleMuteClick }, void 0, _jsx(VolumeIcon, {})), _jsx("div", { className: "VolumeSlider-slider" }, void 0, _jsx(Slider, { min: 0, max: 100, step: 1, value: this.props.volume, onChange: this.handleVolumeChange }))); }; return Volume; }(React.Component); export { Volume as default }; Volume.propTypes = process.env.NODE_ENV !== "production" ? { className: PropTypes.string, volume: PropTypes.number, muted: PropTypes.bool, onVolumeChange: PropTypes.func, onMute: PropTypes.func, onUnmute: PropTypes.func } : {}; //# sourceMappingURL=Volume.js.map
src/js/main.js
NGU2016/gallery-picture
import React from 'react'; import ReactDOM from 'react-dom'; import "../style/main.css" var imageData=require('../data/imgData.json'); import ImgFigure from "../component/ImgFigure.js"; import ControllerUI from "../component/Controller.js"; //将信息转换成图片路径 var imageDatas=(function imgUrl(imgDataArray) { for(var i=0,j=imgDataArray.length;i<j;i++){ var singleImgData=imgDataArray[i]; singleImgData.imgUrl=require('../img/'+singleImgData.fileName); imgDataArray[i] = singleImgData; } return imgDataArray; })(imageData); function getRangeRandom(low,high){ return Math.ceil(Math.random() *(high-low) +low) } /* * 旋转角度 * */ function get30DegRandom(){ return (Math.random() > 0.5 ?Math.ceil(Math.random() * 30):'-'+Math.ceil(Math.random() * 30)) } class Gallary extends React.Component{ constructor (props) { super(props) this.Constant = { centerPos:{ left:0, right:0 }, hPosRange :{ //水平方向取值范围 leftSecX:[0,0], rightSeX:[0,0], y:[0,0] }, vPosRange:{//垂直方向的取值范围 x:[0,0], topY:[0,0] } }; this.state ={ imgsArrangArr:[ /*{ pos:{ left:'0', top:'0' }, rotate 0, isInverse : false, isCenter:false }*/ ] }; } /*** * 翻转图片 * **/ inverse (index){ return function(){ var imgsArrangeArr = this.state.imgsArrangArr; imgsArrangeArr[index].isInverse =!imgsArrangeArr[index].isInverse; this.setState({ imgsArrangArr : imgsArrangeArr }) }.bind(this) } /** * 利用rearrange函数居中index的图片 * **/ center (index) { return function(){ this.rearrange(index); }.bind(this) } /* *重新布局所有图片 * */ rearrange (centerIndex){ var imgsArrangArr = this.state.imgsArrangArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecx = hPosRange.rightSeX, hPosRangY = hPosRange.y, vPosRangeTopY=vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.ceil(Math.random() * 2), topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangArr.splice(centerIndex,1); //居中图片不需要旋转 imgsArrangeCenterArr[0]={ pos : centerPos, rotate :0, isCenter: true } //取出要布局上侧的图片状态信息 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangArr.length -topImgNum)); imgsArrangeTopArr = imgsArrangArr.splice( topImgSpliceIndex,topImgNum ) //布局位于上侧的图片 imgsArrangeTopArr.forEach(function(value,index){ imgsArrangeTopArr[index]={ pos:{ top : getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]), left : getRangeRandom(vPosRangeX[0],vPosRangeX[1]) }, rotate :get30DegRandom(), isCenter :false } }) //布局左右两侧的图片 for(var i=0,j=imgsArrangArr.length,k=j/2;i<j;i++){ var hPosRangeLORX =null; //前半部分 if(i<k){ hPosRangeLORX = hPosRangeLeftSecX; }else{ hPosRangeLORX = hPosRangeRightSecx; } imgsArrangArr[i]={ pos :{ top:getRangeRandom(hPosRangY[0],hPosRangY[1]), left :getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter : false } } if(imgsArrangeTopArr && imgsArrangeTopArr[0]){ imgsArrangArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]) } imgsArrangArr.splice(centerIndex,0,imgsArrangeCenterArr[0]); this.setState({ imgsArrangArr:imgsArrangArr }) } //组件加载以后为每张图片计算范围 componentDidMount (){ //舞台的大小 var stageDom=ReactDOM.findDOMNode(this.refs.stage), stageW= stageDom.scrollWidth, stageH= stageDom.scrollHeight, halfStageW = Math.ceil(stageW/2), halfStageH = Math.ceil(stageH/2); //拿到imgfigure的大小 var imgFigureDom = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW=imgFigureDom.scrollWidth, imgH=imgFigureDom.scrollHeight, halfImgW=Math.ceil(imgW/2), halfImgH=Math.ceil(imgH/2); //计算中心位置点 this.Constant.centerPos ={ left:halfStageW-halfImgW, top:halfStageH-halfImgH } this.Constant.hPosRange.leftSecX[0] = 0-halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW-halfImgW * 3; this.Constant.hPosRange.rightSeX[0] = halfStageW+halfImgW; this.Constant.hPosRange.rightSeX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = 0-halfImgH; this.Constant.hPosRange.y[1] = stageH-halfImgH; this.Constant.vPosRange.topY[0] = 0-halfImgH; this.Constant.vPosRange.topY[1] = halfStageH-halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW -imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0) } render(){ var controllerUnits=[],imgFigures=[]; imageDatas.forEach(function (value,index) { if(!this.state.imgsArrangArr[index]){ this.state.imgsArrangArr[index]={ pos:{ left:0, top:0 }, rotate :0, isInverse:false, isCenter : false } } controllerUnits.push(<ControllerUI key={index} center = {this.center(index)} inverse = {this.inverse(index) } data={value} arrange ={this.state.imgsArrangArr[index]} />) imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure'+ index} arrange ={this.state.imgsArrangArr[index]} inverse={this.inverse(index)} center = {this.center(index)} />) }.bind(this)) return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ) } } ReactDOM.render( <Gallary/>, document.getElementById('root') );
src/icons/IosFilmOutline.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosFilmOutline extends React.Component { render() { if(this.props.bare) { return <g> <path d="M56,88v336h400V88H56z M128,408H72v-48h56V408z M128,344H72v-48h56V344z M128,280H72v-48h56V280z M128,216H72v-48h56V216z M128,152H72v-48h56V152z M368,408H144V264h224V408z M368,248H144V104h224V248z M440,408h-56v-48h56V408z M440,344h-56v-48h56V344z M440,280h-56v-48h56V280z M440,216h-56v-48h56V216z M440,152h-56v-48h56V152z"></path> </g>; } return <IconBase> <path d="M56,88v336h400V88H56z M128,408H72v-48h56V408z M128,344H72v-48h56V344z M128,280H72v-48h56V280z M128,216H72v-48h56V216z M128,152H72v-48h56V152z M368,408H144V264h224V408z M368,248H144V104h224V248z M440,408h-56v-48h56V408z M440,344h-56v-48h56V344z M440,280h-56v-48h56V280z M440,216h-56v-48h56V216z M440,152h-56v-48h56V152z"></path> </IconBase>; } };IosFilmOutline.defaultProps = {bare: false}
jenkins-design-language/src/js/components/material-ui/svg-icons/action/launch.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionLaunch = (props) => ( <SvgIcon {...props}> <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/> </SvgIcon> ); ActionLaunch.displayName = 'ActionLaunch'; ActionLaunch.muiName = 'SvgIcon'; export default ActionLaunch;
ui/src/containers/Visualisations/TemplateWeekdaysActivity/Viewer.js
LearningLocker/learninglocker
import React from 'react'; import PropTypes from 'prop-types'; import SourceResults from 'ui/containers/VisualiseResults/SourceResults'; import ColumnChartResults from 'ui/containers/VisualiseResults/ColumnChartResults'; /** * @param {string} props.visualisationId * @param {boolean} props.showSourceView */ const Viewer = ({ visualisationId, showSourceView, }) => { if (showSourceView) { return <SourceResults id={visualisationId} />; } return <ColumnChartResults id={visualisationId} />; }; Viewer.propTypes = { visualisationId: PropTypes.string.isRequired, showSourceView: PropTypes.bool.isRequired, }; export default React.memo(Viewer);
src/js/components/icons/base/Checkbox.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-checkbox`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'checkbox'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><rect width="20" height="20" x="2" y="2" fill="none" stroke="#000" strokeWidth="2"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Checkbox'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
public/controllers/management/components/management/ruleset/main-ruleset.js
wazuh/wazuh-kibana-app
/* * Wazuh app - React component for registering agents. * Copyright (C) 2015-2022 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component } from 'react'; // Redux import store from '../../../../../redux/store'; import WzReduxProvider from '../../../../../redux/wz-redux-provider'; //Wazuh ruleset tables(rules, decoder, lists) import WzRulesetOverview from './ruleset-overview'; //Information about rule or decoder import WzRuleInfo from './rule-info'; import WzDecoderInfo from './decoder-info'; import WzRulesetEditor from './ruleset-editor'; import WzListEditor from './list-editor'; export default class WzRuleset extends Component { _isMount = false; constructor(props) { super(props); this.state = {}; //Init state empty to avoid fails when try to read any parameter and this.state is not defined yet this.store = store; } UNSAFE_componentWillMount() { this._isMount = true; this.store.subscribe(() => { const state = this.store.getState().rulesetReducers; if (this._isMount) { this.setState(state); this.setState({ selectedTabId: state.section }); } }); } componentWillUnmount() { this._isMount = false; // When the component is going to be unmounted the ruleset state is reset const { ruleInfo, decoderInfo, listInfo, fileContent, addingRulesetFile } = this.state; if ( !window.location.href.includes('rules?tab=rules') && (!ruleInfo && !decoderInfo && !listInfo && !fileContent, !addingRulesetFile) ) { this.store.dispatch({ type: 'RESET' }); } } render() { const { ruleInfo, decoderInfo, listInfo, fileContent, addingRulesetFile } = this.state; return ( <WzReduxProvider> {(ruleInfo && <WzRuleInfo />) || (decoderInfo && <WzDecoderInfo />) || (listInfo && <WzListEditor clusterStatus={this.props.clusterStatus} />) || ((fileContent || addingRulesetFile) && ( <WzRulesetEditor logtestProps={this.props.logtestProps} clusterStatus={this.props.clusterStatus} /> )) || <WzRulesetOverview clusterStatus={this.props.clusterStatus} />} </WzReduxProvider> ); } }
packages/material-ui-icons/legacy/NetworkWifiOutlined.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M3.53 10.94L12 21.5l8.47-10.56c-.43-.33-3.66-2.95-8.47-2.95s-8.04 2.62-8.47 2.95z" /></React.Fragment> , 'NetworkWifiOutlined');
src/svg-icons/navigation/more-vert.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationMoreVert = (props) => ( <SvgIcon {...props}> <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); NavigationMoreVert = pure(NavigationMoreVert); NavigationMoreVert.displayName = 'NavigationMoreVert'; NavigationMoreVert.muiName = 'SvgIcon'; export default NavigationMoreVert;
src/components/HomePage.js
tony-luisi/eMazon-Me
import React from 'react' import SearchBar from './SearchBar' import StoresListings from './StoresListings' import testData from '.././data/thumbnailSampleData' class HomePage extends React.Component { constructor(props) { super(props) } render () { return ( <div className="homePage"> <SearchBar /> <StoresListings storeTNs={testData} /> </div> )}} export default HomePage
src/Controller.js
dog-days/react-router-controller
import React from 'react'; //基本的配置,会在当前类和./index.jsx中使用。 export let ControllerConfig = {}; //所有view是否是第一次载入状态 const allViewFirstLoad = {}; /** * url风格定义如下,跟php框架的Yii一致,例如: * pathname=/main/about/id/100/appid/aiermu * 上面的pathname会解析为 * {contollerId: 'main',viewId: 'about',id: "100",appid: 'aiermu'} * 然后根据解析的参数运行对应的控制器和渲染页面 * 所有控制器必须继承这个基类控制器 */ export default class Contoller { /** * 设置默认配置,app初始化设置,必须要先调用这个去配置。 * @param {config} config 一些配置 * {controllerDir:'',viewDir: ''} */ static set(config) { ControllerConfig = config; } /** * 根据传进来的参数,检查url的params是否符合controller指定的格式 * @param { object } params eg. {contollerId: 'main',viewId: 'about',id: "100",appid: 'aiermu'} * @param { array } paramsSetting eg. ['id','appid'] */ checkParams(params, paramsSetting) { let flag = true; paramsSetting.forEach(v => { if (!~Object.keys(params).indexOf(v)) { flag = false; } }); if (!flag) { console.error('参数跟指定的不一致,将返回404页面。'); } return flag; } /** * 根据param获取router path * @param { object } params 格式如下 * {contollerId: 'main',viewId: 'about',id: "100",appid: 'aiermu' } * @return { string } eg. /main/about/id/100/appid/aiermu */ getReactRouterPath(params) { let path = '/'; for (let k in params) { let v = params[k]; if (k === 'controllerId' || k === 'viewId') { path += `${v}/`; } else { path += `:__${k}__/:${k}/`; } } let pathArr = path.split('/'); pathArr.pop(); path = pathArr.join('/'); return path; } /** * @param {object} config 一些配置 * @param {object} params 路由配置参数 * eg. {contollerId: 'main',viewId: 'about',id: "100",appid: 'aiermu' } * @param {object} ViewComponent react view 组件,如果存在,覆盖默认的。 */ render(config, params, ViewComponent) { if (!params) { console.error('Controller render: 第二参数params参数是必填项!'); } if (!ControllerConfig.readControllerFile) { console.error('请先配置Controller的controller文件夹和view文件夹的路径读取方法!'); } //begin--页面title设置 if (this.suffixTitle) { config.title += this.suffixTitle; } document.title = config.title; config.params = params; //end--页面title设置 //view的部分props let newProps = { actions: config.actions, viewConfig: config, params, }; let returnConfig = { //存放所有的view config配置 viewConfig: config, LayoutComponent: this.LayoutComponent, path: this.getReactRouterPath(params), }; if (ViewComponent) { returnConfig.component = props => { return <ViewComponent {...props} {...newProps} />; }; return returnConfig; } else { let viewId = params.viewId; let controllerId = params.controllerId; //--begin view组件是否是第一次载入 if (!allViewFirstLoad[controllerId]) { allViewFirstLoad[controllerId] = {}; } let firstLoad = allViewFirstLoad[controllerId][viewId]; if (allViewFirstLoad[controllerId][viewId] === undefined) { //为undefined就是第一次载入 firstLoad = true; } //--end view组件是否是第一次载入 return ( ControllerConfig.readViewFile && ControllerConfig.readViewFile( viewId, controllerId, firstLoad ).then(ViewComponent => { //标记view组件第一次已经载入 allViewFirstLoad[controllerId][viewId] = false; returnConfig.component = props => { return <ViewComponent {...props} {...newProps} />; }; return returnConfig; }) ); } } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
gutenye/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-and-default"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/components/todo/TodoList.js
leonpapazianis/react-boilerplate
import React from 'react'; import { TodoItem } from './TodoItem'; export const TodoList = props => ( <div className="Todo-List"> <ul> {props.todos.map(todo => <TodoItem handleToggle={props.handleToggle} key={todo.id} {...todo}/>)} </ul> </div> ); TodoList.propTypes = { todos: React.PropTypes.array.isRequired, };
ui/js/pages/page/PageItem.js
ericsoderberg/pbc-web
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const PageItem = (props) => { const { align, className, item: page } = props; const classNames = ['item__container', className]; const itemClassNames = ['item']; if (align) { itemClassNames.push(`item--${align}`); } let path; if (page.path === 'home') { path = '/'; } else if (page.path && page.path[0] !== '/') { path = `/${page.path}`; } else { path = `/pages/${page._id}`; } return ( <Link className={classNames.join(' ')} to={path}> <div className={itemClassNames.join(' ')}> <span className="item__name">{page.name}</span> </div> </Link> ); }; PageItem.propTypes = { align: PropTypes.oneOf(['start', 'center', 'end']), className: PropTypes.string, item: PropTypes.object.isRequired, }; PageItem.defaultProps = { align: undefined, className: undefined, }; export default PageItem;
examples/todomvc/containers/TodoApp.js
blackxored/redux-devtools
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Header from '../components/Header'; import MainSection from '../components/MainSection'; import * as TodoActions from '../actions/TodoActions'; class TodoApp extends Component { render() { const { todos, actions } = this.props; return ( <div> <Header addTodo={actions.addTodo} /> <MainSection todos={todos} actions={actions} /> </div> ); } } function mapState(state) { return { todos: state.todos }; } function mapDispatch(dispatch) { return { actions: bindActionCreators(TodoActions, dispatch) }; } export default connect(mapState, mapDispatch)(TodoApp);
src/decorators/withViewport.js
18621032336/Three
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
docs/app/Examples/collections/Grid/Variations/GridExampleColumnCount.js
ben174/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleColumnCount = () => ( <Grid> <Grid.Row columns={3}> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row columns={4}> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row columns={5}> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleColumnCount
app/components/H3/index.js
Rohitbels/KolheshwariIndustries
import React from 'react'; function H3(props) { return ( <h3 {...props} /> ); } export default H3;
src/parser/demonhunter/havoc/modules/talents/DemonBlades.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import Events from 'parser/core/Events'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import { formatThousands, formatPercentage } from 'common/format'; /** * Example Report: https://www.warcraftlogs.com/reports/4GR2pwAYW8KtgFJn/#fight=6&source=18 */ class DemonBlades extends Analyzer{ furyGain = 0; furyWaste = 0; damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.DEMON_BLADES_TALENT.id); if (!this.active) { return; } this.addEventListener(Events.energize.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY), this.onEnergizeEvent); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.DEMON_BLADES_FURY), this.onDamageEvent); } onEnergizeEvent(event) { this.furyGain += event.resourceChange; this.furyWaste += event.waste; } onDamageEvent(event) { this.damage += event.amount; } get furyPerMin() { return ((this.furyGain - this.furyWaste) / (this.owner.fightDuration/60000)).toFixed(2); } get suggestionThresholds() { return { actual: this.furyWaste / this.furyGain, isGreaterThan: { minor: 0.03, average: 0.07, major: 0.1, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<> Be mindful of your Fury levels and spend it before capping your Fury due to <SpellLink id={SPELLS.DEMON_BLADES_TALENT.id} />.</>) .icon(SPELLS.DEMON_BLADES_TALENT.icon) .actual(`${formatPercentage(actual)}% Fury wasted`) .recommended(`${formatPercentage(recommended)}% is recommended.`); }); } statistic(){ const effectiveFuryGain = this.furyGain - this.furyWaste; return ( <TalentStatisticBox talent={SPELLS.DEMON_BLADES_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(6)} value={( <> {this.furyPerMin} <small>Fury per min</small> <br /> {this.owner.formatItemDamageDone(this.damage)} </> )} tooltip={( <> {formatThousands(this.damage)} Total damage<br /> {effectiveFuryGain} Effective Fury gained<br /> {this.furyGain} Total Fury gained<br /> {this.furyWaste} Fury wasted </> )} /> ); } } export default DemonBlades;
src/icons/Chatbox.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Chatbox extends React.Component { render() { if(this.props.bare) { return <g> <path d="M124.3,400H277c14.4,0,14.4,0.1,21.3,5.2S384,464,384,464v-64h3.7c42.2,0,76.3-31.8,76.3-71.4V119.7 c0-39.6-34.2-71.7-76.3-71.7H124.3C82.2,48,48,80.1,48,119.7v208.9C48,368.2,82.2,400,124.3,400z"></path> </g>; } return <IconBase> <path d="M124.3,400H277c14.4,0,14.4,0.1,21.3,5.2S384,464,384,464v-64h3.7c42.2,0,76.3-31.8,76.3-71.4V119.7 c0-39.6-34.2-71.7-76.3-71.7H124.3C82.2,48,48,80.1,48,119.7v208.9C48,368.2,82.2,400,124.3,400z"></path> </IconBase>; } };Chatbox.defaultProps = {bare: false}
src/renderer.js
bcgodfrey91/git-in-the-game
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import rootReducer from './reducers/index'; import Home from './components/Home'; import Settings from './components/Settings'; import App from './components/App'; import Dashboard from './components/Dashboard'; const store = createStore(rootReducer); let user = JSON.parse(localStorage.getItem('username')); ReactDOM.render( <Provider store={store}> <Router history={hashHistory}> <Route path='/' component={App}> { user ? <IndexRoute component={Home} /> : <IndexRoute component={Settings} /> } <Route path='/login' component={Settings} /> <Route path='/home' component={Home} /> <Route path='/dashboard' component={Dashboard} /> </Route> </Router> </Provider>, document.getElementById('app') );
src/svg-icons/action/settings-phone.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsPhone = (props) => ( <SvgIcon {...props}> <path d="M13 9h-2v2h2V9zm4 0h-2v2h2V9zm3 6.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.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.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 9v2h2V9h-2z"/> </SvgIcon> ); ActionSettingsPhone = pure(ActionSettingsPhone); ActionSettingsPhone.displayName = 'ActionSettingsPhone'; export default ActionSettingsPhone;
assets/main.js
rmccue/new-list-tables
import React from 'react'; import ReactDOM from 'react-dom'; import CommentsTable from './Tables/Comments'; import PostsTable from './Tables/Posts'; const init = () => { let Component; switch ( window.nlkOptions.id ) { case 'comments': Component = CommentsTable; break; case 'posts': Component = PostsTable; break; } ReactDOM.render( <Component {...window.nlkOptions} />, document.getElementById( 'nlk-table-wrap' ) ); }; document.addEventListener( 'DOMContentLoaded', init ); if ( module.hot ) { module.hot.accept(() => { console.log( 'reload app please' ); }); }
src/screens/Shared/Detail.js
alphasp/pxview
import React, { Component } from 'react'; import { StyleSheet, Text, View, InteractionManager, Platform, LayoutAnimation, UIManager, DeviceEventEmitter, } from 'react-native'; import { connect } from 'react-redux'; import { withTheme } from 'react-native-paper'; import analytics from '@react-native-firebase/analytics'; import Share from 'react-native-share'; import ActionButton from 'react-native-action-button'; import { AndroidBackHandler } from 'react-navigation-backhandler'; import enhanceSaveImage from '../../components/HOC/enhanceSaveImage'; import IllustDetailContent from '../../components/IllustDetailContent'; import PXHeader from '../../components/PXHeader'; import PXViewPager from '../../components/PXViewPager'; import DetailInfoModal from '../../components/DetailInfoModal'; import PXBottomSheet from '../../components/PXBottomSheet'; import PXBottomSheetButton from '../../components/PXBottomSheetButton'; import PXBottomSheetCancelButton from '../../components/PXBottomSheetCancelButton'; import BookmarkIllustButton from '../../components/BookmarkIllustButton'; import Loader from '../../components/Loader'; import PXTouchable from '../../components/PXTouchable'; import PXThumbnail from '../../components/PXThumbnail'; import HeaderInfoButton from '../../components/HeaderInfoButton'; import HeaderSaveImageButton from '../../components/HeaderSaveImageButton'; import HeaderMenuButton from '../../components/HeaderMenuButton'; import * as browsingHistoryIllustsActionCreators from '../../common/actions/browsingHistoryIllusts'; import * as muteUsersActionCreators from '../../common/actions/muteUsers'; import * as illustDetailActionCreators from '../../common/actions/illustDetail'; import { makeGetDetailItem } from '../../common/selectors'; import { SCREENS } from '../../common/constants'; import { globalStyleVariables, globalStyles } from '../../styles'; const THUMBNAIL_SIZE = 30; const styles = StyleSheet.create({ content: { flex: 1, width: globalStyleVariables.WINDOW_WIDTH, }, headerTitleContainer: { flex: 1, alignItems: Platform.OS === 'android' ? 'flex-start' : 'center', ...Platform.select({ ios: { maxWidth: globalStyleVariables.WINDOW_WIDTH - 150, }, }), }, headerThumnailNameContainer: { flexDirection: 'row', alignItems: 'center', }, nameContainer: { flexDirection: 'column', marginLeft: 10, }, headerText: { color: '#fff', }, headerRightContainer: { flexDirection: 'row', alignItems: 'center', }, }); class Detail extends Component { constructor(props) { super(props); this.state = { mounting: true, isActionButtonVisible: true, isOpenMenuBottomSheet: false, isOpenDetailInfoModal: false, selectedImageIndex: null, }; this.listViewOffset = 0; if (Platform.OS === 'android') { /* eslint no-unused-expressions: ["error", { "allowShortCircuit": true }] */ UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true); } } componentDidMount() { const { illustId, item, isFromDeepLink, addBrowsingHistoryIllusts, fetchIllustDetail, } = this.props; InteractionManager.runAfterInteractions(() => { if (this.detailView) { this.setState({ mounting: false }); } if (isFromDeepLink) { fetchIllustDetail(illustId); analytics().logEvent(`Screen_${SCREENS.Detail}`, { id: illustId.toString(), fromDeepLink: true, }); } else { this.masterListUpdateListener = DeviceEventEmitter.addListener( 'masterListUpdate', this.handleOnMasterListUpdate, ); addBrowsingHistoryIllusts(item.id); analytics().logEvent(`Screen_${SCREENS.Detail}`, { id: item.id.toString(), }); } }); } componentDidUpdate(prevProps) { const { illustId, isFromDeepLink, illustDetail, addBrowsingHistoryIllusts, } = this.props; const { illustDetail: prevIllustDetail } = prevProps; if ( illustId && isFromDeepLink && illustDetail?.loaded !== prevIllustDetail?.loaded && illustDetail?.item ) { // only add browsing history if item is loaded for illust that open from deep link addBrowsingHistoryIllusts(illustId); } } componentWillUnmount() { if (this.masterListUpdateListener) { this.masterListUpdateListener.remove(); } } handleOnScrollDetailImageList = (e) => { // Simple fade-in / fade-out animation const CustomLayoutLinear = { duration: 100, create: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, update: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, delete: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, }; // Check if the user is scrolling up or down by confronting the new scroll position with your own one const currentOffset = e.nativeEvent.contentOffset.y; const direction = currentOffset > 0 && currentOffset >= this.listViewOffset ? 'down' : 'up'; // If the user is scrolling down (and the action-button is still visible) hide it const isActionButtonVisible = direction === 'up' || currentOffset === 0; if (isActionButtonVisible !== this.state.isActionButtonVisible) { LayoutAnimation.configureNext(CustomLayoutLinear); this.setState({ isActionButtonVisible }); } this.listViewOffset = currentOffset; }; handleOnPressImage = (index) => { const { navigation, item } = this.props; const images = item.page_count > 1 ? item.meta_pages.map((page) => page.image_urls.original) : [item.meta_single_page.original_image_url]; navigation.navigate(SCREENS.ImagesViewer, { images, item, viewerIndex: index, }); }; handleOnLongPressImage = (index) => { this.handleOnPressOpenMenuBottomSheet(index); }; handleOnViewPagerPageSelected = (index) => { const { items, addBrowsingHistoryIllusts, navigation } = this.props; if (this.props.index !== undefined && this.props.index !== index) { const { setParams } = navigation; setParams({ index, }); InteractionManager.runAfterInteractions(() => { analytics().logEvent(`Screen_${SCREENS.Detail}`, { id: items[index].id.toString(), fromSwipe: true, }); addBrowsingHistoryIllusts(items[index].id); }); } }; handleOnListEndReached = () => { const { parentListKey } = this.props; DeviceEventEmitter.emit(`onDetailListEndReached`, { parentListKey, }); }; handleOnMasterListUpdate = ({ listKey, items }) => { const { parentListKey, navigation: { setParams }, } = this.props; if (parentListKey === listKey) { setParams({ items }); } }; handleOnPressHeaderBackButton = () => { const { goBack } = this.props.navigation; goBack(); }; handleOnPressOpenMenuBottomSheet = (selectedImageIndex) => { const newState = { isOpenMenuBottomSheet: true, }; if (selectedImageIndex !== null) { newState.selectedImageIndex = selectedImageIndex; } this.setState(newState); }; handleOnCancelMenuBottomSheet = () => { this.setState({ isOpenMenuBottomSheet: false, selectedImageIndex: null, }); }; handleOnPressToggleMuteUser = () => { const { item, isMuteUser, addMuteUser, removeMuteUser } = this.props; if (isMuteUser) { removeMuteUser(item.user.id); } else { addMuteUser({ id: item.user.id, name: item.user.name, profile_image_urls: item.user.profile_image_urls, }); } this.handleOnCancelMenuBottomSheet(); }; handleOnPressShareIllust = () => { const { item } = this.props; const shareOptions = { message: `${item.title} | ${item.user.name} #pxviewr`, url: `https://www.pixiv.net/artworks/${item.id}`, }; Share.open(shareOptions) .then(this.handleOnCancelMenuBottomSheet) .catch(this.handleOnCancelMenuBottomSheet); }; handleOnPressSaveImage = () => { const { saveImage, item } = this.props; const { selectedImageIndex } = this.state; const images = item.page_count > 1 ? item.meta_pages.map((page) => page.image_urls.original) : [item.meta_single_page.original_image_url]; saveImage({ imageUrls: [images[selectedImageIndex]], imageIndex: selectedImageIndex, workId: item.id, workTitle: item.title, workType: item.type, userId: item.user.id, userName: item.user.name, }); this.handleOnCancelMenuBottomSheet(); }; handleOnPressOpenDetailInfoModal = () => { this.setState({ isOpenDetailInfoModal: true, }); }; handleOnCancelDetailInfoModal = () => { this.setState({ isOpenDetailInfoModal: false, }); }; handleOnPressHardwareBackButton = () => { const { isOpenDetailInfoModal } = this.state; if (isOpenDetailInfoModal) { this.setState({ isOpenDetailInfoModal: false, }); return true; } return false; }; renderHeaderTitle = (item) => { const { navigation: { push }, } = this.props; return ( <View style={styles.headerTitleContainer}> <PXTouchable style={styles.headerThumnailNameContainer} onPress={() => push(SCREENS.UserDetail, { userId: item.user.id })} > <PXThumbnail uri={item.user.profile_image_urls.medium} size={THUMBNAIL_SIZE} /> <View style={styles.nameContainer}> <Text style={styles.headerText} ellipsizeMode="tail" numberOfLines={1} > {item.user.name} </Text> <Text style={styles.headerText} ellipsizeMode="tail" numberOfLines={1} > {item.user.account} </Text> </View> </PXTouchable> </View> ); }; renderHeaderRight = (item) => { const images = item.page_count > 1 ? item.meta_pages.map((page) => page.image_urls.original) : [item.meta_single_page.original_image_url]; return ( <View style={styles.headerRightContainer}> <HeaderInfoButton onPress={this.handleOnPressOpenDetailInfoModal} /> <HeaderSaveImageButton imageUrls={images} workId={item.id} workTitle={item.title} workType={item.type} userId={item.user.id} userName={item.user.name} saveAll /> <HeaderMenuButton onPress={() => this.handleOnPressOpenMenuBottomSheet(null)} /> </View> ); }; renderContent = ({ item, index: itemIndex }) => { const { navigation, authUser, route, index } = this.props; return ( <View style={styles.content} key={item.id}> <PXHeader headerTitle={this.renderHeaderTitle(item)} headerRight={this.renderHeaderRight(item)} darkTheme withShadow showBackButton onPressBackButton={this.handleOnPressHeaderBackButton} /> <IllustDetailContent item={item} itemIndex={itemIndex} currentIndex={index} navigation={navigation} route={route} authUser={authUser} onPressImage={this.handleOnPressImage} onLongPressImage={this.handleOnLongPressImage} onScroll={this.handleOnScrollDetailImageList} /> </View> ); }; renderMainContent() { const { items, item, index, isFromDeepLink } = this.props; const { mounting } = this.state; if (mounting) { return <Loader />; } if (isFromDeepLink) { if (!item) { return <Loader />; } return ( <PXViewPager items={[item]} keyExtractor={(vpItem) => vpItem.id.toString()} index={0} renderContent={this.renderContent} onPageSelected={this.handleOnViewPagerPageSelected} onEndReached={this.handleOnListEndReached} /> ); } return ( <PXViewPager items={items} keyExtractor={(vpItem) => vpItem.id.toString()} index={index} renderContent={this.renderContent} onPageSelected={this.handleOnViewPagerPageSelected} onEndReached={this.handleOnListEndReached} /> ); } renderBookmarkButtonIcon = () => { const { item } = this.props; return <BookmarkIllustButton item={item} />; }; render() { const { item, isMuteUser, i18n, navigation, theme, route } = this.props; const { isActionButtonVisible, isOpenDetailInfoModal, isOpenMenuBottomSheet, selectedImageIndex, } = this.state; return ( <AndroidBackHandler onBackPress={this.handleOnPressHardwareBackButton}> <View style={[ globalStyles.container, { backgroundColor: theme.colors.background }, ]} ref={(ref) => (this.detailView = ref)} > {this.renderMainContent()} {isActionButtonVisible && item && ( <ActionButton buttonColor="rgba(255,255,255,1)" bgColor="red" renderIcon={this.renderBookmarkButtonIcon} fixNativeFeedbackRadius /> )} <DetailInfoModal item={item} navigation={navigation} route={route} visible={isOpenDetailInfoModal} onCancel={this.handleOnCancelDetailInfoModal} /> <PXBottomSheet visible={isOpenMenuBottomSheet} onCancel={this.handleOnCancelMenuBottomSheet} > {selectedImageIndex !== null && ( <PXBottomSheetButton onPress={this.handleOnPressSaveImage} iconName="content-save" iconType="material-community" text={i18n.saveImage} /> )} <PXBottomSheetButton onPress={this.handleOnPressShareIllust} iconName="share" iconType="entypo" text={i18n.share} /> <PXBottomSheetButton onPress={this.handleOnPressToggleMuteUser} iconName="user-times" iconType="font-awesome" textStyle={{ marginLeft: 28, }} text={isMuteUser ? i18n.userMuteRemove : i18n.userMuteAdd} /> <PXBottomSheetCancelButton onPress={this.handleOnCancelMenuBottomSheet} textStyle={{ marginLeft: 38, }} text={i18n.cancel} /> </PXBottomSheet> </View> </AndroidBackHandler> ); } } export default withTheme( enhanceSaveImage( connect( () => { const getDetailItem = makeGetDetailItem(); return (state, props) => { const item = getDetailItem(state, props); const isMuteUser = item ? state.muteUsers.items.some((m) => m.id === item.user.id) : false; const { illust_id: illustIdFromQS, illustId, items, index, parentListKey, } = props.route.params; const id = parseInt(illustIdFromQS || illustId, 0); return { illustId: id || item.id, illustDetail: state.illustDetail[id], // get illustDetail from api if load from deep link item, isMuteUser, isFromDeepLink: !!id, items, index, parentListKey, authUser: state.auth.user, }; }; }, { ...browsingHistoryIllustsActionCreators, ...muteUsersActionCreators, ...illustDetailActionCreators, }, )(Detail), ), );
tests/react/createElement_string.js
JonathanUsername/flow
// @flow import React from 'react'; class Bar extends React.Component<{}> {} class Foo extends React.Component<{}> { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }
src/app/d3components/utilities/axisLabel.js
cox-auto-kc/react-d3-responsive
'use strict'; import React from 'react'; const AxisLabel = ({w, h, axisLabel, axisType, padding}) => { const translateLabelX = "translate("+(w/2)+","+(h+40)+")"; const translateLabelY = "translate(" + (-40 - padding) + ","+(h/2)+") rotate(270)"; return ( <text className={axisType + "-axis-label"} textAnchor="middle" transform={axisType === 'y' ? translateLabelY : translateLabelX} >{axisLabel}</text> ); }; AxisLabel.propTypes = { w:React.PropTypes.number, h:React.PropTypes.number, padding:React.PropTypes.number, axisLabel:React.PropTypes.string, axisType:React.PropTypes.oneOf(['x','y']) }; AxisLabel.defaultProps = { padding: 0 }; export default AxisLabel;
src/svg-icons/editor/strikethrough-s.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorStrikethroughS = (props) => ( <SvgIcon {...props}> <path d="M7.24 8.75c-.26-.48-.39-1.03-.39-1.67 0-.61.13-1.16.4-1.67.26-.5.63-.93 1.11-1.29.48-.35 1.05-.63 1.7-.83.66-.19 1.39-.29 2.18-.29.81 0 1.54.11 2.21.34.66.22 1.23.54 1.69.94.47.4.83.88 1.08 1.43.25.55.38 1.15.38 1.81h-3.01c0-.31-.05-.59-.15-.85-.09-.27-.24-.49-.44-.68-.2-.19-.45-.33-.75-.44-.3-.1-.66-.16-1.06-.16-.39 0-.74.04-1.03.13-.29.09-.53.21-.72.36-.19.16-.34.34-.44.55-.1.21-.15.43-.15.66 0 .48.25.88.74 1.21.38.25.77.48 1.41.7H7.39c-.05-.08-.11-.17-.15-.25zM21 12v-2H3v2h9.62c.18.07.4.14.55.2.37.17.66.34.87.51.21.17.35.36.43.57.07.2.11.43.11.69 0 .23-.05.45-.14.66-.09.2-.23.38-.42.53-.19.15-.42.26-.71.35-.29.08-.63.13-1.01.13-.43 0-.83-.04-1.18-.13s-.66-.23-.91-.42c-.25-.19-.45-.44-.59-.75-.14-.31-.25-.76-.25-1.21H6.4c0 .55.08 1.13.24 1.58.16.45.37.85.65 1.21.28.35.6.66.98.92.37.26.78.48 1.22.65.44.17.9.3 1.38.39.48.08.96.13 1.44.13.8 0 1.53-.09 2.18-.28s1.21-.45 1.67-.79c.46-.34.82-.77 1.07-1.27s.38-1.07.38-1.71c0-.6-.1-1.14-.31-1.61-.05-.11-.11-.23-.17-.33H21z"/> </SvgIcon> ); EditorStrikethroughS = pure(EditorStrikethroughS); EditorStrikethroughS.displayName = 'EditorStrikethroughS'; EditorStrikethroughS.muiName = 'SvgIcon'; export default EditorStrikethroughS;
public/components/MyApp.js
rolandfung/project-ipsum
import React from 'react'; import actions from '../actions/ipsumActions.js'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { renderChart } from '../D3graphTemplate'; import { Panel, Grid, Row, Col, PageHeader, Button, Image} from 'react-bootstrap'; import request from '../util/restHelpers'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import barGraph from './BarGraph'; import _ from 'underscore'; import MyAppHistory from './MyAppHistory'; import Select from 'react-select'; class MyApp extends React.Component { constructor(props) { super(props); this.state = { lineGraphRoute: null, resizefunc: null, loading1: false, loading2: false }; } getAndGraphTodaysData(){ this.setState({loading1: true}, () => { // call 24 hr bar graph data and render request.post('/getStats/serverTotalsForApp', { appid: this.props.state.appSelection.id, hours: 24 }, (err, data) => { if (err) {console.log('ERROR', err); return; } var data = JSON.parse(data.text); var output = []; Object.keys(data).forEach((serverId) => { output.push({ value: data[serverId].statValue, label: data[serverId].hostname, id: Number(serverId) }); }); // for relative server load bar graph this.props.dispatch(actions.CHANGE_APP_SERVER_TOTALS(output)); this.setState({loading1: false}, () => { barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => { return -obj.value; })); }); }); }); //For routes line Graph this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE('/Total')); var appId = this.props.state.appSelection.id; this.setState({loading2: true}, () => { request.post('/getStats/app', {appId: appId, hours: 24}, //TODO figure out how to keep track of desired hours, have user settings/config in store? (err, res) => { this.setState({loading2: false}) if (err) { console.log("Error getting Server Data", err); } this.props.dispatch(actions.ADD_SERVER_DATA(res.body)); this.setState({lineGraphRoute: this.props.state.graphData[0].route}); renderChart('lineGraph', this.props.state.graphData[0].data); }); this.setState({resizefunc: this.resizedb()}, () => { window.addEventListener('resize', this.state.resizefunc); }) }) } componentDidMount() { this.getAndGraphTodaysData(); } resizedb() { var redraw = function() { // linegraph this.updateGraph({value: this.state.lineGraphRoute}); // horizontal bar graph barGraph('todayBarGraph', _.sortBy(this.props.state.appServerTotals, (obj) => { return -obj.value; })); } return _.debounce(redraw.bind(this), 500) } componentWillUnmount() { window.removeEventListener('resize', this.state.resizefunc); } updateGraph(value) { !value ? null : this.setState({lineGraphRoute: value.value}); this.props.dispatch(actions.ADD_LINE_GRAPH_TITLE("/" + value.value)); d3.select('#lineGraph > svg').remove(); renderChart('lineGraph', _.findWhere(this.props.state.graphData, {route: value.value}).data); } tableLinkForm(cell) { return ( <Link to="/myServer"> <div onClick={this.goToServer.bind(this, cell)}> {_.findWhere(this.props.state.servers, {id: cell}).active} </div> </Link> ); } goToServer(cell) { this.props.dispatch(actions.ADD_SERVER_SELECTION(_.findWhere(this.props.state.servers, {id: cell}))); } enumFormatter(cell, row, enumObject) { return enumObject(cell); } render() { var sortedServerTotals = _.sortBy(this.props.state.appServerTotals, (obj) => { return -obj.value; }); var statusData = sortedServerTotals.map((total, idx) => { return { label: total.label, status: _.findWhere(this.props.state.servers, {id: total.id}).active, id: total.id } }) var lineGraphOptions = this.props.state.graphData.map((graph) => {return {label: '/'+graph.route, value: graph.route}}) return ( <Grid> <Row><Col xs={12} md={12}> <PageHeader> {this.props.state.appSelection.appname} <small>at a glance</small> </PageHeader> </Col></Row> <Row className='serverStatContainer'> <Col xs={12} lg={12} > <div style={{display:'flex', justifyContent:'space-between'}}> <h2>What{'\''}s Happening</h2> <span className='pull-right'> <Button onClick={this.getAndGraphTodaysData.bind(this)} bsStyle='primary'>Refresh</Button> </span> </div> <Panel header={<div>Routes</div>} > <Grid fluid> <Row> <Col xs={12} lg={12}> {this.state.loading2 ? <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}><img src="assets/loading.gif" /></div> : <div> <Select value={this.state.lineGraphRoute} multi={false} options={lineGraphOptions} onChange={this.updateGraph.bind(this)} /> <h3 className="linegraph-title">Hits Per Hour Today</h3> <p className="xAxis-subtitle">for {this.props.state.lineGraphTitle == '/Total' ? 'all monitored routes' : <i>{this.props.state.lineGraphTitle}</i>}</p> <div id="lineGraph"></div> <h5 className="xAxis-title">Hours Ago</h5> </div> } </Col> </Row> </Grid> </Panel> </Col> </Row> <Row> <Col xs={12} md={12}> <Panel header={<h1>Server Information</h1>}> <Grid fluid> <Row> <Col xs={12} md={6}> <h4>Relative load (24 hr)</h4> {this.state.loading1 ? <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}><img src="assets/loading.gif" /></div> : <div id="todayBarGraph"></div> } </Col> <Col xs={12} md={6}> <h4>Status</h4> <BootstrapTable ref='table' data={statusData} striped={true} hover={true} > <TableHeaderColumn isKey={true} dataField="label" dataAlign="center">Hostname</TableHeaderColumn> <TableHeaderColumn dataAlign="center" dataField="id" dataFormat={this.enumFormatter} formatExtraData={this.tableLinkForm.bind(this)}>See Stats</TableHeaderColumn> </BootstrapTable> </Col> </Row> </Grid> </Panel> </Col> </Row> <MyAppHistory /> </Grid> ) } } MyApp = connect(state => ({ state: state }))(MyApp); export default MyApp
app/scripts/views/typography.js
transmute-industries/monarch-portal
import React from 'react' export function addr (addr) { return <code className='webui-address'>{addr}</code> }
cheesecakes/admin/admin/src/containers/LocaleToggle/index.js
strapi/strapi-examples
/* * * LanguageToggle * */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { bindActionCreators } from 'redux'; import cn from 'classnames'; import { ButtonDropdown, DropdownItem, DropdownMenu, DropdownToggle } from 'reactstrap'; import { selectLocale } from 'containers/LanguageProvider/selectors'; import { changeLocale } from 'containers/LanguageProvider/actions'; import { languages } from 'i18n'; import styles from './styles.scss'; export class LocaleToggle extends React.Component { // eslint-disable-line state = { isOpen: false }; getFlagUrl = (locale) => { switch (locale) { case 'en': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/us.svg'; case 'pt-BR': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/br.svg'; case 'zh': case 'zh-Hans': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/cn.svg'; case 'ar': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/sa.svg'; case 'ko': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/kr.svg'; case 'ja': return 'https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/jp.svg'; default: return `https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.1.0/flags/4x3/${locale}.svg`; } } toggle = () => this.setState(prevState => ({ isOpen: !prevState.isOpen })); render() { const { locale } = this.props; return ( <div className={styles.localeToggle}> <ButtonDropdown isOpen={this.state.isOpen} toggle={this.toggle}> <DropdownToggle className={styles.localeDropdownContent}> <span>{locale}</span> <img src={this.getFlagUrl(locale)} alt={locale} /> </DropdownToggle> <DropdownMenu className={cn(styles.localeDropdownMenu, this.props.isLogged ? '' : styles.localeDropdownMenuNotLogged)}> {languages.map(language => ( <DropdownItem key={language} onClick={() => this.props.changeLocale(language)} className={cn(styles.localeToggleItem, locale === language ? styles.localeToggleItemActive : '')}> {language.toUpperCase()} </DropdownItem> ))} </DropdownMenu> </ButtonDropdown> </div> ); } } LocaleToggle.propTypes = { changeLocale: PropTypes.func.isRequired, isLogged: PropTypes.bool.isRequired, locale: PropTypes.string.isRequired, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); function mapDispatchToProps(dispatch) { return bindActionCreators( { changeLocale, }, dispatch, ); } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
lib/manager.js
pressly/scene-router
// @flow import React from 'react' import route from 'trie-route' import * as constants from './constants' import { Scene } from './scene' import type { SceneConfig, Route, Router, SceneResolver, SceneRejecter, RouterExtra, GestureStatus } from './types' // types ////////////////////////////////////////////////////////////////////// type SceneWrapProps = { sceneRef: (ref: any) => void, customSceneConfig: SceneConfig, route: Route, onGesture: (status: GestureStatus) => void } // internal functions ///////////////////////////////////////////////////////// const mergeDefaultSceneOptions = (options: SceneConfig): SceneConfig => { return { side: constants.FromRight, threshold: 30, gesture: true, reset: false, backgroundColor: 'white', ...options } } // what we have to do is, const mergeCustomSceneOptions = (currentOpts: SceneConfig, userOpts: SceneConfig): SceneConfig => { // currentOpts is the one which was configured at scene decorator. // userOpts is the one which was passed by router to chnage the behaviour // so, we need to make sure to remove userOpts.path and merge it with currentOpts delete userOpts.path return { ...currentOpts, ...userOpts } } // SceneManager /////////////////////////////////////////////////////////////// export class SceneManager { router: Router resolver: ?SceneResolver rejecter: ?SceneRejecter constructor() { this.router = route.create() } register(SceneWrap: Function, originalSceneConfig: SceneConfig) { this.router.path(originalSceneConfig.path, (params: Object = {}, qs: Object = {}, extra: RouterExtra) => { const { path, props, customSceneConfig } = extra const route = { path, params, qs, props, config: null } this.resolver && this.resolver(SceneWrap, route, originalSceneConfig, customSceneConfig) }) } request(path: string, props: ?Object = {}, customSceneConfig: SceneConfig) { const err = this.router.process(path, { path, props, customSceneConfig }) if (err) { this.rejecter && this.rejecter(`'${path}' ${err}`) } } // this callback will be set by Router class setSceneResolver(sceneResolver: SceneResolver) { this.resolver = sceneResolver } setSceneRejecter(sceneRejecter: SceneRejecter) { this.rejecter = sceneRejecter } } export const sceneManager = new SceneManager() // dcecorators ///////////////////////////////////////////////////////////////// export const scene = (originalSceneConfig: SceneConfig): Function => { originalSceneConfig = mergeDefaultSceneOptions(originalSceneConfig) return (WrapComponent: Function): Function => { const SceneWrap = (props: SceneWrapProps): React.Element<any> => { const { customSceneConfig, route, onGesture } = props const sceneConfig = mergeCustomSceneOptions(originalSceneConfig, customSceneConfig) return ( <Scene ref={props.sceneRef} WrapComponent={WrapComponent} sceneConfig={sceneConfig} route={route} onGesture={onGesture}/> ) } sceneManager.register(SceneWrap, originalSceneConfig) return WrapComponent } }
admin/client/App/screens/Home/components/ListTile.js
rafmsou/keystone
import React from 'react'; import { Link } from 'react-router'; /** * Displays information about a list and lets you create a new one. */ var ListTile = React.createClass({ propTypes: { count: React.PropTypes.string, hideCreateButton: React.PropTypes.bool, href: React.PropTypes.string, label: React.PropTypes.string, path: React.PropTypes.string, spinner: React.PropTypes.object, }, render () { var opts = { 'data-list-path': this.props.path, }; return ( <div className="dashboard-group__list" {...opts}> <span className="dashboard-group__list-inner"> <Link to={this.props.href} className="dashboard-group__list-tile"> <div className="dashboard-group__list-label">{this.props.label}</div> <div className="dashboard-group__list-count">{this.props.spinner || this.props.count}</div> </Link> {/* If we want to create a new list, we append ?create, which opens the create form on the new page! */} {(!this.props.hideCreateButton) && ( <Link to={this.props.href + '?create'} className="dashboard-group__list-create octicon octicon-plus" title="Criar" tabIndex="-1" /> )} </span> </div> ); }, }); module.exports = ListTile;
app/components/ReleaseHeader.js
jackokerman/discogs-dj
import React from 'react'; import { Table } from 'react-bootstrap'; const ReleaseHeader = (props) => { const { label, releaseDate, styles } = props; return ( <Table condensed> <tbody> <tr> <td>Label</td> <td>{label}</td> </tr> <tr> <td>Released</td> <td>{releaseDate}</td> </tr> <tr> <td>Styles</td> <td>{styles}</td> </tr> </tbody> </Table> ); }; ReleaseHeader.propTypes = { label: React.PropTypes.string.isRequired, releaseDate: React.PropTypes.string.isRequired, styles: React.PropTypes.string.isRequired, }; export default ReleaseHeader;
components/OrderedList.js
hellobrian/carbon-components-react
import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; const propTypes = { children: PropTypes.node, className: PropTypes.string, nested: PropTypes.bool, }; const defaultProps = { nested: false, }; const OrderedList = ({ children, className, nested, ...other }) => { const classNames = classnames('bx--list--ordered', className, { 'bx--list--nested': nested, }); return ( <ol className={classNames} {...other}> {children} </ol> ); }; OrderedList.propTypes = propTypes; OrderedList.defaultProps = defaultProps; export default OrderedList;
examples/todos-with-undo/components/App.js
neighborhood999/redux
import React from 'react' import Footer from './Footer' import AddTodo from '../containers/AddTodo' import VisibleTodoList from '../containers/VisibleTodoList' import UndoRedo from '../containers/UndoRedo' const App = () => ( <div> <AddTodo /> <VisibleTodoList /> <Footer /> <UndoRedo /> </div> ) export default App
src/EventRowMixin.js
manishksmd/react-scheduler-smartdata
import PropTypes from 'prop-types'; import React from 'react'; import { findDOMNode } from 'react-dom'; import EventCell from './EventCell'; import getHeight from 'dom-helpers/query/height'; import { accessor, elementType } from './utils/propTypes'; import { segStyle } from './utils/eventLevels'; import { isSelected } from './utils/selection'; /* eslint-disable react/prop-types */ export default { propTypes: { slots: PropTypes.number.isRequired, end: PropTypes.instanceOf(Date), start: PropTypes.instanceOf(Date), selected: PropTypes.object, eventPropGetter: PropTypes.func, titleAccessor: accessor, // @Appointment field info declaration patientNameAccessor: accessor, clinicianImageAccessor: accessor, clinicianNameAccessor: accessor, appointmentTypeAccessor: accessor, appointmentTimeAccessor: accessor, appointmentAddressAccessor: accessor, coPayAccessor: accessor, soapNoteTitleAccessor: accessor, setProfileTitleAccessor: accessor, staffsAccessor: accessor, isRecurrenceAccessor: accessor, isRecurrenceEditAccessor: accessor, isEditAccessor: accessor, isDeleteAccessor: accessor, isCancelAccessor: accessor, isUnCancelAccessor: accessor, isApproveAccessor: accessor, cancellationReasonAccessor: accessor, isAppointmentRenderedAccessor: accessor, isVideoCallAccessor: accessor, isAppoinmentCancelledAccessor: accessor, practitionerNameAccessor: accessor, statusNameAccessor: accessor, usersAvailability: PropTypes.object, allDayAccessor: accessor, startAccessor: accessor, endAccessor: accessor, eventComponent: elementType, eventWrapperComponent: elementType.isRequired, onSelect: PropTypes.func }, defaultProps: { segments: [], selected: {}, slots: 7 }, renderEvent(props, event) { let { eventPropGetter, selected, start, end , startAccessor , endAccessor , titleAccessor , patientNameAccessor , clinicianImageAccessor , clinicianNameAccessor , appointmentTypeAccessor , appointmentTimeAccessor , appointmentAddressAccessor , coPayAccessor , soapNoteTitleAccessor , setProfileTitleAccessor , staffsAccessor , isRecurrenceAccessor , isRecurrenceEditAccessor , isEditAccessor , isDeleteAccessor , isCancelAccessor , isApproveAccessor , isUnCancelAccessor , cancellationReasonAccessor , isAppointmentRenderedAccessor , isVideoCallAccessor , isAppoinmentCancelledAccessor , practitionerNameAccessor , statusNameAccessor , usersAvailability , allDayAccessor, eventComponent , eventWrapperComponent , onSelect } = props; return ( <EventCell event={event} eventWrapperComponent={eventWrapperComponent} eventPropGetter={eventPropGetter} onSelect={onSelect} selected={isSelected(event, selected)} startAccessor={startAccessor} endAccessor={endAccessor} titleAccessor={titleAccessor} patientNameAccessor={patientNameAccessor} clinicianImageAccessor={clinicianImageAccessor} clinicianNameAccessor={clinicianNameAccessor} appointmentTypeAccessor={appointmentTypeAccessor} appointmentTimeAccessor={appointmentTimeAccessor} appointmentAddressAccessor={appointmentAddressAccessor} coPayAccessor={coPayAccessor} soapNoteTitleAccessor={soapNoteTitleAccessor} setProfileTitleAccessor={setProfileTitleAccessor} staffsAccessor={staffsAccessor} isRecurrenceAccessor={isRecurrenceAccessor} isRecurrenceEditAccessor={isRecurrenceEditAccessor} isEditAccessor={isEditAccessor} isDeleteAccessor={isDeleteAccessor} isCancelAccessor={isCancelAccessor} isUnCancelAccessor={isUnCancelAccessor} isApproveAccessor={isApproveAccessor} cancellationReasonAccessor={cancellationReasonAccessor} isAppointmentRenderedAccessor={isAppointmentRenderedAccessor} isVideoCallAccessor={isVideoCallAccessor} isAppoinmentCancelledAccessor={isAppoinmentCancelledAccessor} practitionerNameAccessor={practitionerNameAccessor} statusNameAccessor={statusNameAccessor} allDayAccessor={allDayAccessor} usersAvailability={usersAvailability} slotStart={start} slotEnd={end} eventComponent={eventComponent} /> ) }, renderSpan(props, len, key, content = ' ', left){ let { slots } = props; let customClass = `rbc-row-segment custom-class-${left}`; return ( <div key={key} className={customClass} style={segStyle(Math.abs(len), slots)}> {content} </div> ) }, getRowHeight(){ getHeight(findDOMNode(this)) } }
src/client.js
niketpathak/npk-website
/** * @author Niket Pathak. (http://www.niketpathak.com/) * * Copyright © 2014-present. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import deepForceUpdate from 'react-deep-force-update'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import App from './components/App'; import createFetch from './createFetch'; import history from './history'; import { updateMeta } from './DOMUtils'; import router from './router'; /* eslint-disable global-require */ // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, // Universal HTTP client fetch: createFetch({ baseUrl: window.App.apiUrl, }), }; // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration const scrollPositionsHistory = {}; if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } let onRenderComplete = function initialRenderComplete() { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); onRenderComplete = function renderComplete(route, location) { document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }; }; const container = document.getElementById('app'); let appInstance; let currentLocation = history.location; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; try { // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve({ ...context, path: location.pathname, query: queryString.parse(location.search), }); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } appInstance = ReactDOM.render( <App context={context}>{route.component}</App>, container, () => onRenderComplete(route, location), ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (action && currentLocation.key === location.key) { window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./router', () => { if (appInstance) { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } onLocationChange(currentLocation); }); }
src/frontend/src/components/auth/LoginDialog.js
ziroby/dmassist
import React from 'react'; import './LoginDialog.css'; class LoginDialog extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { this.props.onLogin(this.state.value); event.preventDefault(); } render() { return <form className="LoginDialog" onSubmit={this.handleSubmit}> <label htmlFor="username">User Name:&nbsp; <input type="text" id="username" name="username" value={this.state.value} onChange={this.handleChange}/> </label> <br/> <label htmlFor="password">Password:&nbsp; <input type="text" placeholder="No Password Needed" id="password" name="password" disabled /> </label> <br/> <input type="submit" value="Submit" /> </form> } } export default LoginDialog;
src/components/app.js
blueeyess/redux-intermediate
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> ); } }
app/components/home/Home.js
dingo-d/wp-api
import React from 'react'; import DataStore from './../../stores/DataStore.js'; class Home extends React.Component { render() { let allData = DataStore.getAll(); return ( <div> <h1>Hello World</h1> </div> ); } } module.exports = Home;
react/src/browser/app/Root.js
janprasil/mi-vmm-product-quality-rating
/* @flow */ import App from './App'; import BrowserHistory from 'react-history/BrowserHistory'; import React from 'react'; import { Provider as Redux, connect } from 'react-redux'; import { StaticRouter } from 'react-router'; import { setLocation } from '../../common/app/actions'; type RouterProps = { dispatch: () => void, pathname: ?string, }; // TODO: Use ControlledRouter once it will be released. const Router = ({ dispatch, pathname }: RouterProps) => ( <BrowserHistory> {({ history, action, location }) => { setImmediate(() => { dispatch(setLocation(location)); }); return ( <StaticRouter action={action} blockTransitions={history.block} key={pathname} // github.com/yahoo/react-intl/issues/234#issuecomment-163366518 location={location} onPush={history.push} onReplace={history.replace} > <App /> </StaticRouter> ); }} </BrowserHistory> ); const ConnectedRouter = connect(state => ({ pathname: state.app.location && state.app.location.pathname, }))(Router); type RootProps = { store: Object, }; const Root = ({ store }: RootProps) => ( <Redux store={store}> <ConnectedRouter /> </Redux> ); export default Root;
src/svg-icons/communication/rss-feed.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationRssFeed = (props) => ( <SvgIcon {...props}> <circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/> </SvgIcon> ); CommunicationRssFeed = pure(CommunicationRssFeed); CommunicationRssFeed.displayName = 'CommunicationRssFeed'; export default CommunicationRssFeed;
src/svg-icons/image/brightness-2.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness2 = (props) => ( <SvgIcon {...props}> <path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/> </SvgIcon> ); ImageBrightness2 = pure(ImageBrightness2); ImageBrightness2.displayName = 'ImageBrightness2'; ImageBrightness2.muiName = 'SvgIcon'; export default ImageBrightness2;
docs/src/sections/PaginationSection.js
dozoisch/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function PaginationSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="pagination">Pagination</Anchor> <small>Pagination</small> </h2> <p>Provide pagination links for your site or app with the multi-page pagination component. Set <code>items</code> to the number of pages. <code>activePage</code> prop dictates which page is active</p> <ReactPlayground codeText={Samples.PaginationBasic} /> <h4><Anchor id="pagination-more">More options</Anchor></h4> <p>such as <code>first</code>, <code>last</code>, <code>previous</code>, <code>next</code>, <code>boundaryLinks</code> and <code>ellipsis</code>.</p> <ReactPlayground codeText={Samples.PaginationAdvanced} /> <h3><Anchor id="pagination-props">Props</Anchor></h3> <PropTable component="Pagination"/> </div> ); }
src/icons/GlyphMail.js
ipfs/webui
import React from 'react' const GlyphMail = props => ( <svg viewBox='0 0 100 100' {...props}> <path d='M47.94 55.76a2.12 2.12 0 0 0 2.83 0L81.5 28.91a5.85 5.85 0 0 0-4.67-2.52H24.08a7.27 7.27 0 0 0-5.35 2.74zm-9.78-4.92L17.24 31.76A5.62 5.62 0 0 0 17 33.5v33.77A5.76 5.76 0 0 0 18.47 71zm22.68.06l20.51 20.77a6.49 6.49 0 0 0 1.7-4.4V33.5a7.19 7.19 0 0 0-.24-1.83z' /> <path d='M58.62 52.84L52.71 58a5.09 5.09 0 0 1-6.71-.06l-5.61-5.12-19.51 20a7.38 7.38 0 0 0 3.25.78h52.7a6.38 6.38 0 0 0 2-.31z' /> </svg> ) export default GlyphMail
frontend/src/pages/org-admin/org-logs-file-update.js
miurahr/seahub
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; import { seafileAPI } from '../../utils/seafile-api'; import { siteRoot, gettext, lang } from '../../utils/constants'; import { Utils } from '../../utils/utils'; import toaster from '../../components/toast'; import OrgLogsFileUpdateEvent from '../../models/org-logs-file-update'; import ModalPortal from '../../components/modal-portal'; import FileUpdateDetailDialog from '../../components/dialog/org-logs-file-update-detail'; import '../../css/org-logs.css'; moment.locale(lang); class OrgLogsFileUpdate extends Component { constructor(props) { super(props); this.state = { page: 1, pageNext: false, eventList: [], userSelected: '', repoSelected: '', isItemFreezed: false, showDetails: false, repoID: '', commitID: '' }; } componentDidMount() { let page = this.state.page; let email = this.state.userSelected; let repoID = this.state.repoSelected; this.initData(email, repoID, page); } initData = (email, repoID, page) => { seafileAPI.orgAdminListFileUpdate(email, repoID, page).then(res => { let eventList = res.data.log_list.map(item => { return new OrgLogsFileUpdateEvent(item); }); this.setState({ eventList: eventList, pageNext: res.data.page_next, page: res.data.page, }); }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } onChangePageNum = (e, num) => { e.preventDefault(); let page = this.state.page; if (num == 1) { page = page + 1; } else { page = page - 1; } let email = this.state.userSelected; let repoID = this.state.repoSelected; this.initData(email, repoID, page); } toggleCancelDetail = () => { this.setState({ showDetails: !this.state.showDetails }); } onDetails = (e, fileEvent) => { e.preventDefault(); this.setState({ showDetails: !this.state.showDetails, repoID: fileEvent.repo_id, commitID: fileEvent.repo_commit_id }); } filterUser = (userSelected) => { this.setState({ userSelected: userSelected }); } filterRepo = (repoSelected) => { this.setState({ repoSelected: repoSelected }); } render() { let eventList = this.state.eventList; return ( <div className="cur-view-content"> { (this.state.userSelected || this.state.repoSelected) && <React.Fragment> {this.state.userSelected && <span className="audit-unselect-item" onClick={this.filterUser.bind(this, null)}> <span className="no-deco">{this.state.userSelected}</span>{' ✖'} </span> } {this.state.repoSelected && <span className="audit-unselect-item" onClick={this.filterRepo.bind(this, null)}> <span className="no-deco">{this.state.repoSelected}</span>{' ✖'} </span> } </React.Fragment> } <table> <thead> <tr> <th width="25%">{gettext('User')}</th> <th width="17%">{gettext('Date')}</th> <th width="25%">{gettext('Library')}</th> <th width="33%">{gettext('Action')}</th> </tr> </thead> <tbody> {eventList.map((item, index) => { return ( <FileUpdateItem key={index} fileEvent={item} isItemFreezed={this.state.isItemFreezed} onDetails={this.onDetails} filterUser={this.filterUser} filterRepo={this.filterRepo} userSelected={this.state.userSelected} repoSelected={this.state.repoSelected} /> ); })} </tbody> </table> <div className="paginator"> {this.state.page != 1 && <a href="#" onClick={(e) => this.onChangePageNum(e, -1)}>{gettext('Previous')}</a>} {(this.state.page != 1 && this.state.pageNext) && <span> | </span>} {this.state.pageNext && <a href="#" onClick={(e) => this.onChangePageNum(e, 1)}>{gettext('Next')}</a>} </div> {this.state.showDetails && <ModalPortal> <FileUpdateDetailDialog repoID={this.state.repoID} commitID={this.state.commitID} toggleCancel={this.toggleCancelDetail} /> </ModalPortal> } </div> ); } } const propTypes = { filterUser: PropTypes.func.isRequired, filterRepo: PropTypes.func.isRequired, onDetails: PropTypes.func.isRequired, userSelected: PropTypes.string.isRequired, repoSelected: PropTypes.string.isRequired, isItemFreezed: PropTypes.bool.isRequired, }; class FileUpdateItem extends React.Component { constructor(props) { super(props); this.state = { highlight: false, showMenu: false, isItemMenuShow: false, userDropdownOpen: false, repoDropdownOpen: false, }; } onMouseEnter = () => { if (!this.props.isItemFreezed) { this.setState({ showMenu: true, highlight: true, }); } } onMouseLeave = () => { if (!this.props.isItemFreezed) { this.setState({ showMenu: false, highlight: false }); } } toggleUserDropdown = () => { this.setState({ userDropdownOpen: !this.state.userDropdownOpen }); } renderUser = (fileEvent) => { if (!fileEvent.user_email) { return gettext('Anonymous User'); } return ( <span> <a href={siteRoot + 'org/useradmin/info/' + fileEvent.user_email + '/'}>{fileEvent.user_name}</a>{' '} <Dropdown size='sm' isOpen={this.state.userDropdownOpen} toggle={this.toggleUserDropdown} className={this.state.highlight ? '' : 'vh'} tag="span"> <DropdownToggle tag="i" className="sf-dropdown-toggle sf2-icon-caret-down"></DropdownToggle> <DropdownMenu> <DropdownItem onClick={this.props.filterUser.bind(this, fileEvent.user_email)}> {gettext('Only Show')}{' '}<span className="font-weight-bold">{fileEvent.user_name}</span> </DropdownItem> </DropdownMenu> </Dropdown> </span> ); } toggleRepoDropdown = () => { this.setState({ repoDropdownOpen: !this.state.repoDropdownOpen }); } renderRepo = (fileEvent) => { let repoName = 'Deleted'; if (fileEvent.repo_name) { repoName = fileEvent.repo_name; } return ( <span> <span>{repoName}</span> { fileEvent.repo_name && <Dropdown size='sm' isOpen={this.state.repoDropdownOpen} toggle={this.toggleRepoDropdown} className={this.state.highlight ? '' : 'vh'} > <DropdownToggle tag="i" className="sf-dropdown-toggle sf2-icon-caret-down"></DropdownToggle> <DropdownMenu> <DropdownItem size='sm' onClick={this.props.filterRepo.bind(this, fileEvent.repo_name)}> {gettext('Only Show')}{' '} <span className="font-weight-bold">{fileEvent.repo_name}</span> </DropdownItem> </DropdownMenu> </Dropdown> } </span> ); } renderAction = (fileEvent) => { if (fileEvent.repo_encrypted || !fileEvent.repo_id) { return <td>{fileEvent.description}</td>; } return ( <td>{fileEvent.description} <a className="font-weight-normal text-muted ml-1" href='#' onClick={(e) => this.props.onDetails(e, fileEvent)}>{gettext('Details')}</a> </td> ); } render() { let { fileEvent } = this.props; if (this.props.userSelected && fileEvent.user_email !== this.props.userSelected ) { return null; } else if (this.props.repoSelected && fileEvent.repo_name !== this.props.repoSelected) { return null; } else { return ( <tr className={this.state.highlight ? 'tr-highlight' : ''} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}> <td>{this.renderUser(fileEvent)}</td> <td>{moment(fileEvent.time).format('YYYY-MM-DD HH:mm:ss')}</td> <td>{this.renderRepo(fileEvent)}</td> {this.renderAction(fileEvent)} </tr> ); } } } FileUpdateItem.propTypes = propTypes; export default OrgLogsFileUpdate;
src/components/Footer/Footer.js
history007/karma-one
import React from 'react'; const Footer = () => <footer >< /footer> export {Footer}; export default Footer;
test/App-test.js
octopitus/feather
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import styles from '../src/App.css' import { App, Counter } from '../src/App.js'; test('render 2 counters component', t => { const wrapper = shallow(React.createElement(App)); t.is(wrapper.find('.' + styles.container).length, 1); });
test/test_helper.js
MrmRed/test
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/index.js
anuragaryan/webpack-react-redux-starter
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
src/client.js
mattijsbliek/record-client
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; import makeRouteHooksSafe from './helpers/makeRouteHooksSafe'; const client = new ApiClient(); // Three different types of scroll behavior available. // Documented here: https://github.com/rackt/scroll-behavior const scrollableHistory = useScroll(createHistory); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), scrollableHistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <ReduxRouter routes={getRoutes(store)} /> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
src/svg-icons/device/signal-cellular-connected-no-internet-2-bar.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet2Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet2Bar = pure(DeviceSignalCellularConnectedNoInternet2Bar); DeviceSignalCellularConnectedNoInternet2Bar.displayName = 'DeviceSignalCellularConnectedNoInternet2Bar'; DeviceSignalCellularConnectedNoInternet2Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet2Bar;
src/addons/Pagination/Pagination.js
Semantic-Org/Semantic-UI-React
import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { ModernAutoControlledComponent as Component, createPaginationItems, customPropTypes, getUnhandledProps, } from '../../lib' import Menu from '../../collections/Menu' import PaginationItem from './PaginationItem' /** * A component to render a pagination. */ export default class Pagination extends Component { getInitialAutoControlledState() { return { activePage: 1 } } handleItemClick = (e, { value: nextActivePage }) => { const { activePage: prevActivePage } = this.state // Heads up! We need the cast to the "number" type there, as `activePage` can be a string if (+prevActivePage === +nextActivePage) return this.setState({ activePage: nextActivePage }) _.invoke(this.props, 'onPageChange', e, { ...this.props, activePage: nextActivePage }) } handleItemOverrides = (active, type, value) => (predefinedProps) => ({ active, type, key: `${type}-${value}`, onClick: (e, itemProps) => { _.invoke(predefinedProps, 'onClick', e, itemProps) if (itemProps.type !== 'ellipsisItem') this.handleItemClick(e, itemProps) }, }) render() { const { 'aria-label': ariaLabel, boundaryRange, disabled, ellipsisItem, siblingRange, totalPages, } = this.props const { activePage } = this.state const items = createPaginationItems({ activePage, boundaryRange, hideEllipsis: _.isNil(ellipsisItem), siblingRange, totalPages, }) const rest = getUnhandledProps(Pagination, this.props) return ( <Menu {...rest} aria-label={ariaLabel} pagination role='navigation'> {_.map(items, ({ active, type, value }) => PaginationItem.create(this.props[type], { defaultProps: { content: value, disabled, value, }, overrideProps: this.handleItemOverrides(active, type, value), }), )} </Menu> ) } } Pagination.propTypes = { /** A pagination item can have an aria label. */ 'aria-label': PropTypes.string, /** Initial activePage value. */ defaultActivePage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** Index of the currently active page. */ activePage: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** Number of always visible pages at the beginning and end. */ boundaryRange: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** A pagination can be disabled. */ disabled: PropTypes.bool, /** A shorthand for PaginationItem. */ ellipsisItem: customPropTypes.itemShorthand, /** A shorthand for PaginationItem. */ firstItem: customPropTypes.itemShorthand, /** A shorthand for PaginationItem. */ lastItem: customPropTypes.itemShorthand, /** A shorthand for PaginationItem. */ nextItem: customPropTypes.itemShorthand, /** A shorthand for PaginationItem. */ pageItem: customPropTypes.itemShorthand, /** A shorthand for PaginationItem. */ prevItem: customPropTypes.itemShorthand, /** * Called on change of an active page. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onPageChange: PropTypes.func, /** Number of always visible pages before and after the current one. */ siblingRange: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** Total number of pages. */ totalPages: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, } Pagination.autoControlledProps = ['activePage'] Pagination.defaultProps = { 'aria-label': 'Pagination Navigation', boundaryRange: 1, ellipsisItem: '...', firstItem: { 'aria-label': 'First item', content: '«', }, lastItem: { 'aria-label': 'Last item', content: '»', }, nextItem: { 'aria-label': 'Next item', content: '⟩', }, pageItem: {}, prevItem: { 'aria-label': 'Previous item', content: '⟨', }, siblingRange: 1, } Pagination.Item = PaginationItem
docs/src/app/AppRoutes.js
spiermar/material-ui
import React from 'react'; import { Route, Redirect, IndexRoute, } from 'react-router'; // Here we define all our material-ui ReactComponents. import Master from './components/Master'; import Home from './components/pages/Home'; import Prerequisites from './components/pages/get-started/Prerequisites'; import Installation from './components/pages/get-started/Installation'; import Usage from './components/pages/get-started/Usage'; import Examples from './components/pages/get-started/Examples'; import ServerRendering from './components/pages/get-started/ServerRendering'; import Colors from './components/pages/customization/Colors'; import Themes from './components/pages/customization/Themes'; import InlineStyles from './components/pages/customization/InlineStyles'; import AppBarPage from './components/pages/components/AppBar/Page'; import AutoCompletePage from './components/pages/components/AutoComplete/Page'; import AvatarPage from './components/pages/components/Avatar/Page'; import BadgePage from './components/pages/components/Badge/Page'; import CardPage from './components/pages/components/Card/Page'; import CircularProgressPage from './components/pages/components/CircularProgress/Page'; import CheckboxPage from './components/pages/components/Checkbox/Page'; import DatePicker from './components/pages/components/DatePicker/Page'; import DialogPage from './components/pages/components/Dialog/Page'; import DividerPage from './components/pages/components/Divider/Page'; import DrawerPage from './components/pages/components/Drawer/Page'; import DropDownMenuPage from './components/pages/components/DropDownMenu/Page'; import FlatButtonPage from './components/pages/components/FlatButton/Page'; import FloatingActionButtonPage from './components/pages/components/FloatingActionButton/Page'; import FontIconPage from './components/pages/components/FontIcon/Page'; import GridListPage from './components/pages/components/GridList/Page'; import IconButtonPage from './components/pages/components/IconButton/Page'; import IconMenuPage from './components/pages/components/IconMenu/Page'; import ListPage from './components/pages/components/List/Page'; import LinearProgressPage from './components/pages/components/LinearProgress/Page'; import PaperPage from './components/pages/components/Paper/Page'; import MenuPage from './components/pages/components/Menu/Page'; import PopoverPage from './components/pages/components/Popover/Page'; import RaisedButtonPage from './components/pages/components/RaisedButton/Page'; import RefreshIndicatorPage from './components/pages/components/RefreshIndicator/Page'; import RadioButtonPage from './components/pages/components/RadioButton/Page'; import SelectField from './components/pages/components/SelectField/Page'; import SliderPage from './components/pages/components/Slider/Page'; import SnackbarPage from './components/pages/components/Snackbar/Page'; import SvgIconPage from './components/pages/components/SvgIcon/Page'; import SubheaderPage from './components/pages/components/Subheader/Page'; import TablePage from './components/pages/components/Table/Page'; import TabsPage from './components/pages/components/Tabs/Page'; import TextFieldPage from './components/pages/components/TextField/Page'; import TimePickerPage from './components/pages/components/TimePicker/Page'; import TogglePage from './components/pages/components/Toggle/Page'; import ToolbarPage from './components/pages/components/Toolbar/Page'; import Community from './components/pages/discover-more/Community'; import Contributing from './components/pages/discover-more/Contributing'; import Showcase from './components/pages/discover-more/Showcase'; import RelatedProjects from './components/pages/discover-more/RelatedProjects'; import StepperPage from './components/pages/components/Stepper/Page'; /** * Routes: https://github.com/rackt/react-router/blob/master/docs/api/components/Route.md * * Routes are used to declare your view hierarchy. * * Say you go to http://material-ui.com/#/components/paper * The react router will search for a route named 'paper' and will recursively render its * handler and its parent handler like so: Paper > Components > Master */ const AppRoutes = ( <Route path="/" component={Master}> <IndexRoute component={Home} /> <Route path="home" component={Home} /> <Redirect from="get-started" to="/get-started/prerequisites" /> <Route path="get-started"> <Route path="prerequisites" component={Prerequisites} /> <Route path="installation" component={Installation} /> <Route path="usage" component={Usage} /> <Route path="examples" component={Examples} /> <Route path="server-rendering" component={ServerRendering} /> </Route> <Redirect from="customization" to="/customization/themes" /> <Route path="customization"> <Route path="colors" component={Colors} /> <Route path="themes" component={Themes} /> <Route path="inline-styles" component={InlineStyles} /> </Route> <Redirect from="components" to="/components/app-bar" /> <Route path="components"> <Route path="app-bar" component={AppBarPage} /> <Route path="auto-complete" component={AutoCompletePage} /> <Route path="avatar" component={AvatarPage} /> <Route path="badge" component={BadgePage} /> <Route path="card" component={CardPage} /> <Route path="circular-progress" component={CircularProgressPage} /> <Route path="checkbox" component={CheckboxPage} /> <Route path="date-picker" component={DatePicker} /> <Route path="dialog" component={DialogPage} /> <Route path="divider" component={DividerPage} /> <Route path="drawer" component={DrawerPage} /> <Route path="dropdown-menu" component={DropDownMenuPage} /> <Route path="font-icon" component={FontIconPage} /> <Route path="flat-button" component={FlatButtonPage} /> <Route path="floating-action-button" component={FloatingActionButtonPage} /> <Route path="grid-list" component={GridListPage} /> <Route path="icon-button" component={IconButtonPage} /> <Route path="icon-menu" component={IconMenuPage} /> <Route path="list" component={ListPage} /> <Route path="linear-progress" component={LinearProgressPage} /> <Route path="paper" component={PaperPage} /> <Route path="menu" component={MenuPage} /> <Route path="popover" component={PopoverPage} /> <Route path="refresh-indicator" component={RefreshIndicatorPage} /> <Route path="radio-button" component={RadioButtonPage} /> <Route path="raised-button" component={RaisedButtonPage} /> <Route path="select-field" component={SelectField} /> <Route path="svg-icon" component={SvgIconPage} /> <Route path="slider" component={SliderPage} /> <Route path="snackbar" component={SnackbarPage} /> <Route path="stepper" component={StepperPage} /> <Route path="subheader" component={SubheaderPage} /> <Route path="table" component={TablePage} /> <Route path="tabs" component={TabsPage} /> <Route path="text-field" component={TextFieldPage} /> <Route path="time-picker" component={TimePickerPage} /> <Route path="toggle" component={TogglePage} /> <Route path="toolbar" component={ToolbarPage} /> </Route> <Redirect from="discover-more" to="/discover-more/community" /> <Route path="discover-more"> <Route path="community" component={Community} /> <Route path="contributing" component={Contributing} /> <Route path="showcase" component={Showcase} /> <Route path="related-projects" component={RelatedProjects} /> </Route> </Route> ); export default AppRoutes;
src/components/Layout/SimpleHeader.js
yining1023/thesisBook
import React from 'react' import {Link} from 'react-router-dom' import s from './SimpleHeader.css' import logo from '../../img/itp-logo-tisch.svg' import {Drawer, IconButton} from 'material-ui' import MenuIcon from 'material-ui/svg-icons/navigation/menu' import SimpleFilterMenu from '../SimpleFilterMenu/SimpleFilterMenu' class SimpleHeader extends React.Component { constructor(props) { super(props) this.state = { showDrawer: false, } } componentDidMount() { window.componentHandler.upgradeElement(this.root) window.onresize = () => this.setState({ showDrawer: false }) } componentWillUnmount() { window.componentHandler.downgradeElements(this.root) } toggleDrawer() { this.setState({ showDrawer: !this.state.showDrawer, }) } render() { return ( <header className={`mdl-layout__header ${s.header}`} ref={node => (this.root = node)}> <div className={`mdl-layout__header-row ${s.row}`}> <Link className={`mdl-layout-title`} to="/"> <img className={s.title} src={logo} alt={"ITP Thesis 2017"} /> </Link> <div className="mdl-layout-spacer" /> <div className={s.desktop}> <SimpleFilterMenu /> </div> <div className={s.mobile}> <IconButton onTouchTap={this.toggleDrawer.bind(this)}><MenuIcon color="#ffffff" /></IconButton> </div> <Drawer docked={false} width={300} openSecondary={true} open={this.state.showDrawer} onRequestChange={(showDrawer) => this.setState({showDrawer})} containerStyle={{ backgroundColor: '#2b296e' }} > <SimpleFilterMenu /> </Drawer> </div> </header> ) } } export default SimpleHeader
packages/reactor-kitchensink/src/examples/Tabs/BasicTabs/BasicTabs.js
markbrocato/extjs-reactor
import React from 'react'; import { TabPanel, Container } from '@extjs/ext-react'; export default function BasicTabsExample() { return ( <TabPanel flex={1} shadow defaults={{ cls: "card", layout: "center" }} > <Container title="Tab 1"> <div>By default, tabs are aligned to the top of a view.</div> </Container> <Container title="Tab 2"> <div>A TabPanel can use different animations by setting <code>layout.animation.</code></div> </Container> <Container title="Tab 3"> <span className="action">User tapped Tab 3</span> </Container> </TabPanel> ) }
src/components/modals/NewMarkerMenu/index.js
Guseff/services-on-map-demo
import React, { Component } from 'react'; import ReactModal from 'react-modal'; import NewMarkerForm from '../NewMarkerForm'; import './style.css'; class NewMarkerMenu extends Component { constructor() { super(); this.handleCloseModal = this.handleCloseModal.bind(this); } handleCloseModal() { this.props.closeModal(); } render() { const { showModal_b } = this.props; return ( <div> <ReactModal isOpen={showModal_b} contentLabel="Minimal Modal Example" className="Modal" overlayClassName="Overlay" > <button onClick={this.handleCloseModal}><img alt='' src='blue-close-sm.png' /></button> <NewMarkerForm handleCloseModal={this.handleCloseModal} /> </ReactModal> </div> ); } } export default NewMarkerMenu;
src/svg-icons/content/text-format.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentTextFormat = (props) => ( <SvgIcon {...props}> <path d="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z"/> </SvgIcon> ); ContentTextFormat = pure(ContentTextFormat); ContentTextFormat.displayName = 'ContentTextFormat'; export default ContentTextFormat;
src/app/pages/About.js
skratchdot/web-audio-api-archive
import React, { Component } from 'react'; import Paper from 'material-ui/Paper'; import { connect } from 'react-redux'; import marked from 'marked'; import readmeContents from '~/README.md'; const readmeHtml = marked(readmeContents); class About extends Component { render() { return ( <div style={{ padding: 40 }}> <Paper style={{ padding: 40 }}> <div dangerouslySetInnerHTML={{ __html: readmeHtml }}> </div> </Paper> </div> ); } } export default connect()(About);
src/assets/js/react/components/Template/TemplateActivateButton.js
blueliquiddesigns/gravity-forms-pdf-extended
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { selectTemplate } from '../../actions/templates' import { withRouter } from 'react-router-dom' /** * Renders the button used to trigger the current active PDF template * On click it triggers our Redux action. * * @package Gravity PDF * @copyright Copyright (c) 2020, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 4.1 */ /** * React Component * * @since 4.1 */ export class TemplateActivateButton extends React.Component { /** * @since 4.1 */ static propTypes = { history: PropTypes.object, onTemplateSelect: PropTypes.func, template: PropTypes.object, buttonText: PropTypes.string } /** * Update our route and trigger a Redux action to select the current template * * @param {Object} e Event * * @since 4.1 */ selectTemplate = (e) => { e.preventDefault() e.stopPropagation() this.props.history.push('') this.props.onTemplateSelect(this.props.template.id) } /** * @since 4.1 */ render () { return ( <a onClick={this.selectTemplate} href="#" tabIndex="150" className="button button-primary activate"> {this.props.buttonText} </a> ) } } /** * TemplateActivateButton * Map actions to props * * @param {func} dispatch Redux dispatcher * * @returns {{onTemplateSelect: (function(id=string))}} * * @since 4.1 */ const mapDispatchToProps = dispatch => { return { onTemplateSelect: id => dispatch(selectTemplate(id)) } } /** * Maps our Redux store to our React component * * @since 4.1 */ export default withRouter(connect(null, mapDispatchToProps)(TemplateActivateButton))
doc/src/pages/examples/extend-webgl-renderer.js
mapillary/mapillary-js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import Layout from '@theme/Layout'; import {Code} from '../../js/components/Code'; import {ViewerComponent} from '../../js/components/ViewerComponent'; import {dispose, init} from '../../js/examples/extend-webgl-renderer'; export default function Example() { const title = 'Extend WebGL Renderer'; return ( <Layout title={title} noFooter="true"> <ViewerComponent init={init} dispose={dispose} /> <Code title={title.toLowerCase()} /> </Layout> ); }
src/user/ui/logoutbutton/LogoutButton.js
Solvocracy/solvocracy-dapp
import React from 'react' const LogoutButton = ({ onLogoutUserClick }) => { return( <li className="pure-menu-item"> <a href="#" className="pure-menu-link" onClick={(event) => onLogoutUserClick(event)}>Logout</a> </li> ) } export default LogoutButton
src/app/components/SearchBarOverlay/SearchBar/index.js
ajacksified/reddit-mobile
import './styles.less'; import React from 'react'; import { Form } from '@r/platform/components'; const T = React.PropTypes; function focusInput(x) { if (x) { x.focus(); } } export default class SearchBar extends React.Component { static propTypes = { // onClear: T.func.isRequired, // TODO: uncomment this when we have tracking? subreddit: T.string, initialValue: T.string, placeholder: T.string, }; static defaultProps = { subreddit: '', initialValue: '', placeholder: 'Search Reddit', }; constructor(props) { super(props); this.handleResetInput = this.handleResetInput.bind(this); } componentDidMount() { focusInput(this.refs.input); } handleResetInput() { this.refs.input.value = ''; focusInput(this.refs.input); // this.props.onClear(); // TODO: wire-up tracking } render() { const { placeholder, initialValue, subreddit } = this.props; return ( <Form className='SearchBar' action={ '/search' } > <input key='search-hidden' type='hidden' name='subreddit' value={ subreddit } /> <input key='search' className='SearchBar__input' defaultValue={ initialValue } name='q' placeholder={ placeholder } ref='input' type='search' /> <div className='SearchBar__reset icon icon-x-circled' onClick={ this.handleResetInput } /> </Form> ); } }
src/apps/Hosting/HostingPublishDialog.js
Syncano/syncano-dashboard
import React from 'react'; import Reflux from 'reflux'; import { withRouter } from 'react-router'; import { DialogMixin } from '../../mixins'; import HostingPublishDialogActions from './HostingPublishDialogActions'; import HostinPublishDialogStore from './HostingPublishDialogStore'; import { Dialog } from '../../common'; import { colors as Colors } from 'material-ui/styles'; const PublishDialog = React.createClass({ contextTypes: { params: React.PropTypes.object }, mixins: [ Reflux.connect(HostinPublishDialogStore), DialogMixin ], handlePublishHosting() { const { id } = this.state; HostingPublishDialogActions.publishHosting(id); }, render() { const { instanceName } = this.props.params; const { isLoading, open } = this.state; const containerStyles = { lineHeight: 2 }; return ( <Dialog.Delete key="dialog" ref="dialog" icon="synicon-alert" iconColor={Colors.orange400} title="Set this website as default" onRequestClose={this.handleCancel} open={open} isLoading={isLoading} actions={ <Dialog.StandardButtons disabled={isLoading} submitLabel="Set as default" handleCancel={this.handleCancel} handleConfirm={this.handlePublishHosting} /> } > <div style={containerStyles}> <strong> {'This action will set this website as default.'} </strong> <div> Website will be available at: </div> <div> <a href={`http://${instanceName}.syncano.site`} target="_blank" > {`http://${instanceName}.syncano.site`} </a> </div> <div className="vm-4-t vm-4-b"> Click button to set this website as default </div> </div> </Dialog.Delete> ); } }); export default withRouter(PublishDialog);
packages/material-ui-icons/src/Help.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z" /></g> , 'Help');
plugins/react/frontend/components/common/IFrame/index.js
carteb/carte-blanche
/* eslint-disable max-len */ // based on https://github.com/ryanseddon/react-frame-component import React from 'react'; import path from 'path'; const createHtml = ( componentPath, basePath = '', userFiles, injectTags, commonsChunkFilename ) => { const iframeClientBundle = path.join(basePath, 'iframe-client-bundle.js'); const userBundle = path.join(basePath, 'user-bundle.js'); return `<!DOCTYPE html> <html style="height: 100%; width: 100%; margin: 0; padding: 0;"> <head> ${(injectTags) ? injectTags.join('\n') : ''} <style> ${userFiles && userFiles.styles.join('\n')} </style> </head> <body style="height: 100%; width: 100%; margin: 0; padding: 0;"> <div id="root" style=" display: flex; justify-content: center; align-items: center; height: 100vh; " ></div> <script> window.PLUGIN_NAME = 'react'; window.COMPONENT_PATH = '${componentPath}'; window.COMPONENT_DATA = undefined; </script> ${(commonsChunkFilename !== 'undefined') ? `<script src="/${commonsChunkFilename}"></script>` : ''} <script> ${userFiles && userFiles.scripts.join('\n')} </script> <script src="${iframeClientBundle}"></script> <script src="${userBundle}"></script> </body> </html> `; }; class IFrame extends React.Component { componentDidMount() { const doc = this.iframe.contentDocument; doc.open(); // eslint-disable-next-line max-len doc.write(createHtml( this.props.componentPath, this.props.basePath, this.props.userFiles, this.props.injectTags, this.props.commonsChunkFilename )); doc.close(); this.iframe.contentWindow.INITIAL_COMPONENT_DATA = this.props.variationProps; } componentWillReceiveProps(props) { if (this.iframe.contentWindow.UPDATE_COMPONENT) { this.iframe.contentWindow.UPDATE_COMPONENT(props.variationProps); } } render() { return ( <iframe ref={(ref) => { this.iframe = ref; }} scrolling="no" frameBorder="0" style={{ width: '100%', height: '100%' }} /> ); } } export default IFrame;
RNTester/js/ActivityIndicatorExample.js
clozr/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule ActivityIndicatorExample */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
components/admin/tools/table/actions/DeleteAction.js
resource-watch/resource-watch
import React from 'react'; import PropTypes from 'prop-types'; // Services import { deleteTool } from 'services/tools'; import { toastr } from 'react-redux-toastr'; class DeleteAction extends React.Component { handleOnClickDelete = (e) => { if (e) { e.preventDefault(); e.stopPropagation(); } const { data, authorization } = this.props; toastr.confirm(`Are you sure that you want to delete: "${data.title}"`, { onOk: () => { deleteTool(data.id, authorization) .then(() => { this.props.onRowDelete(data.id); toastr.success('Success', `The tool "${data.id}" - "${data.title}" has been removed correctly`); }) .catch((err) => { toastr.error('Error', `The tool "${data.id}" - "${data.title}" was not deleted. Try again. ${err}`); }); }, }); } render() { return ( <span> <a className="c-btn" href="#delete-dataset" onClick={this.handleOnClickDelete}> Remove </a> </span> ); } } DeleteAction.propTypes = { data: PropTypes.object.isRequired, authorization: PropTypes.string.isRequired, onRowDelete: PropTypes.func.isRequired, }; export default DeleteAction;
blueocean-material-icons/src/js/components/svg-icons/av/airplay.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvAirplay = (props) => ( <SvgIcon {...props}> <path d="M6 22h12l-6-6zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V5h18v12h-4v2h4c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); AvAirplay.displayName = 'AvAirplay'; AvAirplay.muiName = 'SvgIcon'; export default AvAirplay;
benim/src/app.js
SentiyWhen/Ben-IM
import React from 'react' import Login from './container/login/login' import Register from './container/register/register' import AuthRoute from './component/authroute/authroute' import BossInfo from './container/bossinfo/bossinfo' import GeniusInfo from './container/geniusinfo/geniusinfo' import Chat from './component/chat/chat' import Dashboard from './component/dashboard/dashboard' import { Route,Switch } from 'react-router-dom' class App extends React.Component{ render(){ return ( <div> <AuthRoute></AuthRoute> <Switch> <Route path='/bossinfo' component={BossInfo}></Route> <Route path='/geniusinfo' component={GeniusInfo}></Route> <Route path='/login' component={Login}></Route> <Route path='/register' component={Register}></Route> <Route path='/chat/:user' component={Chat}></Route> <Route component={Dashboard}></Route> </Switch> </div> ) } } export default App
packages/ringcentral-widgets-docs/src/app/pages/Components/Line/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/Line'; const LinePage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="Line" description={info.description} /> <CodeExample code={demoCode} title="Line Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default LinePage;
src/components/Profile/UserInfo.js
devcharleneg/twitter-react-app
import React from 'react'; import request from 'superagent'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Profile.css'; import {Row,Col,Image} from 'react-bootstrap'; import AppConstants from '../../constants/AppConstants'; import Session from '../../core/Session'; class UserInfo extends React.Component { constructor(props) { super(props); this.state = { user: null } } componentWillMount() { var self = this; request.get('/api/twitter/account/verify_credentials') .query({accessToken: Session.getAccessToken(), accessTokenSecret: Session.getAccessTokenSecret()}) .end(function(err,res){ if(res) { var user = res.body.response; self.setState({user: user}); console.log('user ',user); } }); } render() { if(this.state.user) { var name = this.state.user.name ? this.state.user.name : ''; var profileImage = this.state.user.profile_image_url ? this.state.user.profile_image_url : null; var screenName = this.state.user.screen_name ? this.state.user.screen_name : ''; var tweetsCount = this.state.user.statuses_count ? this.state.user.statuses_count : 0; var followingCount = this.state.user.friends_count ? this.state.user.friends_count : ''; var followersCount = this.state.user.followers_count ? this.state.user.followers_count : 0; } return ( <div className={s.userInfoContainer}> <Image className={s.thumbnail} src={profileImage} circle responsive/> <div className={s.fullName}>{name}</div> <div className={s.userName}>{screenName ? '@' +screenName : ''}</div> <Row className={s.userStats}> <Col xs={4}> <div className={s.statName}>Tweets</div> <div className={s.statValue}>{tweetsCount}</div> </Col> <Col xs={4}> <div className={s.statName}>Following</div> <div className={s.statValue}>{followingCount}</div> </Col> <Col xs={4}> <div className={s.statName}>Followers</div> <div className={s.statValue}>{followersCount}</div> </Col> </Row> </div> ); } } export default withStyles(s)(UserInfo);
src/components/dashboard/DndWidget.js
metasfresh/metasfresh-webui-frontend
import React, { Component } from 'react'; import { DragSource, DropTarget } from 'react-dnd'; import PropTypes from 'prop-types'; import classnames from 'classnames'; const cardSource = { beginDrag(props) { return { id: props.id, index: props.index, isNew: props.isNew, }; }, }; const cardTarget = { hover(props, monitor) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; if (dragIndex === hoverIndex || monitor.getItem().id === props.id) { return; } props.moveCard && props.moveCard(props.entity, dragIndex, hoverIndex, monitor.getItem()); monitor.getItem().index = hoverIndex; }, drop(props, monitor) { if (monitor.getItem().isNew && props.addCard) { props.addCard(props.entity, monitor.getItem().id); } else { props.onDrop && props.onDrop(props.entity, monitor.getItem().id); } }, }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }; } function connect(connect) { return { connectDropTarget: connect.dropTarget(), }; } export class DndWidget extends Component { constructor(props) { super(props); } render() { const { children, connectDragSource, connectDropTarget, isDragging, className, transparent, removeCard, entity, id, placeholder, index, } = this.props; if (transparent) return <div {...{ className }}>{children}</div>; return connectDragSource( connectDropTarget( <div className={classnames(className, 'dnd-widget', { dragging: isDragging, 'dnd-placeholder': placeholder, })} > {!placeholder && removeCard && ( <i className="meta-icon-trash draggable-icon-remove pointer" onClick={() => removeCard(entity, index, id)} /> )} {children} </div> ) ); } } DndWidget.propTypes = { children: PropTypes.any, connectDragSource: PropTypes.func, connectDropTarget: PropTypes.func, className: PropTypes.string, transparent: PropTypes.bool, removeCard: PropTypes.func, entity: PropTypes.any, id: PropTypes.number, placeholder: PropTypes.string, index: PropTypes.number, isDragging: PropTypes.any, }; export default DragSource((props) => props.entity, cardSource, collect)( DropTarget((props) => props.entity, cardTarget, connect)(DndWidget) );
server/sonar-web/src/main/js/apps/account/components/Home.js
joansmith/sonarqube
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import Favorites from './Favorites'; import FavoriteIssueFilters from './FavoriteIssueFilters'; import FavoriteMeasureFilters from './FavoriteMeasureFilters'; import IssueWidgets from './IssueWidgets'; import { translate } from '../../../helpers/l10n'; const Home = ({ user, favorites, issueFilters, measureFilters }) => ( <div className="page page-limited"> <div className="columns"> <div className="column-third"> <Favorites favorites={favorites}/> {issueFilters && <FavoriteIssueFilters issueFilters={issueFilters}/>} {measureFilters && <FavoriteMeasureFilters measureFilters={measureFilters}/>} </div> <div className="column-third"> <IssueWidgets/> </div> <div className="column-third"> <section> <h2 className="spacer-bottom">{translate('my_profile.groups')}</h2> <ul id="groups"> {user.groups.map(group => ( <li key={group} className="little-spacer-bottom text-ellipsis" title={group}> {group} </li> ))} </ul> </section> <section className="huge-spacer-top"> <h2 className="spacer-bottom">{translate('my_profile.scm_accounts')}</h2> <ul id="scm-accounts"> <li className="little-spacer-bottom text-ellipsis" title={user.login}> {user.login} </li> {user.email && ( <li className="little-spacer-bottom text-ellipsis" title={user.email}> {user.email} </li> )} {user.scmAccounts.map(scmAccount => ( <li key={scmAccount} className="little-spacer-bottom text-ellipsis" title={scmAccount}> {scmAccount} </li> ))} </ul> </section> </div> </div> </div> ); export default Home;
packages/react-server-cli/test/fixtures/BasicPage.js
redfin/react-server
import React from 'react'; class TransitionPage { getElements() { return React.createElement('h1', null, 'Yay!'); } } module.exports = TransitionPage;
src/index.js
kunwardeep/todo-list
import 'babel-polyfill'; import React from 'react'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import '../node_modules/toastr/build/toastr.min.css'; import { Router, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; import routes from './routes'; import configureStore from './store/configureStore'; import loadTodos from './actions/todoActions'; const store = configureStore(); store.dispatch(loadTodos()); render( <Provider store={store}> <Router history={browserHistory} routes={routes}/> </Provider>, document.getElementById('app'));
app/routes.js
DenQ/electron-react-lex
/* eslint flowtype-errors/show-errors: 0 */ import React from 'react'; import { Switch, Route } from 'react-router'; import App from './containers/App'; import CounterPage from './containers/Counter/CounterPage'; import ListAlbumsPage from './containers/pages/list-albums/container'; import AddAlbumPage from './containers/pages/add-album/container'; import EditAlbumPage from './containers/pages/edit-album/container'; import RunAlbumPage from './containers/pages/run-album/container'; import SettingsPage from './containers/pages/settings/container'; export default () => ( <App> <Switch> <Route path="/counter" component={CounterPage} /> <Route path="/add-album" component={AddAlbumPage} /> <Route path="/edit-album/:id" component={EditAlbumPage} /> <Route path="/run-album/:id" component={RunAlbumPage} /> <Route path="/settings" component={SettingsPage} /> <Route path="/" component={ListAlbumsPage} /> </Switch> </App> );
fields/types/password/PasswordField.js
asifiqbal84/keystone
import React from 'react'; import Field from '../Field'; import { Button, FormInput, InputGroup } from 'elemental'; module.exports = Field.create({ displayName: 'PasswordField', getInitialState () { return { passwordIsSet: this.props.value ? true : false, showChangeUI: this.props.mode === 'create' ? true : false, password: '', confirm: '' }; }, valueChanged (which, event) { var newState = {}; newState[which] = event.target.value; this.setState(newState); }, showChangeUI () { this.setState({ showChangeUI: true }, () => this.focus()); }, onCancel () { this.setState({ showChangeUI: false }, () => this.focus()); }, renderValue () { return <FormInput noedit>{this.props.value ? 'password set' : 'password not set'}</FormInput>; }, renderField () { return this.state.showChangeUI ? this.renderFields() : this.renderChangeButton(); }, renderFields () { return ( <InputGroup> <InputGroup.Section grow> <FormInput type="password" name={this.props.path} placeholder="New password" ref="focusTarget" value={this.state.password} onChange={this.valueChanged.bind(this, 'password')} autoComplete="off" /> </InputGroup.Section> <InputGroup.Section grow> <FormInput type="password" name={this.props.paths.confirm} placeholder="Confirm new password" value={this.state.confirm} onChange={this.valueChanged.bind(this, 'confirm')} autoComplete="off" /> </InputGroup.Section> {this.state.passwordIsSet ? <InputGroup.Section><Button onClick={this.onCancel}>Cancel</Button></InputGroup.Section> : null} </InputGroup> ); }, renderChangeButton () { var label = this.state.passwordIsSet ? 'Change Password' : 'Set Password'; return ( <Button ref="focusTarget" onClick={this.showChangeUI}>{label}</Button> ); } });
react-flux-mui/js/material-ui/src/svg-icons/content/delete-sweep.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentDeleteSweep = (props) => ( <SvgIcon {...props}> <path d="M15 16h4v2h-4zm0-8h7v2h-7zm0 4h6v2h-6zM3 18c0 1.1.9 2 2 2h6c1.1 0 2-.9 2-2V8H3v10zM14 5h-3l-1-1H6L5 5H2v2h12z"/> </SvgIcon> ); ContentDeleteSweep = pure(ContentDeleteSweep); ContentDeleteSweep.displayName = 'ContentDeleteSweep'; ContentDeleteSweep.muiName = 'SvgIcon'; export default ContentDeleteSweep;
src/main/webapp/resources/modules/lobby/JoinGameDialog/JoinGameDialog.js
cwoolner/flex-poker
import React from 'react' import Button from 'react-bootstrap/Button' import Modal from 'react-bootstrap/Modal' import Form from 'react-bootstrap/Form' export default ({gameId, showModal, hideDialogCallback, submitFormCallback}) => { return ( <Modal size="sm" show={showModal} onHide={hideDialogCallback}> <Modal.Header closeButton> <Modal.Title>Join Game</Modal.Title> </Modal.Header> <form id="join-game-form" onSubmit={submitFormCallback}> <Modal.Body> <Form.Group> <Form.Label>Current Balance</Form.Label> <Form.Control readOnly defaultValue="100" /> </Form.Group> <Form.Group> <Form.Label>Cost</Form.Label> <Form.Control readOnly defaultValue="10" /> </Form.Group> <Form.Group> <Form.Label>Remaining Balance</Form.Label> <Form.Control readOnly defaultValue="90" /> </Form.Group> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={hideDialogCallback}>Close</Button> <Button type="submit" variant="primary" autoFocus>Join Game</Button> </Modal.Footer> </form> </Modal> ) }
frontend/src/Settings/Notifications/Notifications/AddNotificationPresetMenuItem.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MenuItem from 'Components/Menu/MenuItem'; class AddNotificationPresetMenuItem extends Component { // // Listeners onPress = () => { const { name, implementation } = this.props; this.props.onPress({ name, implementation }); }; // // Render render() { const { name, implementation, ...otherProps } = this.props; return ( <MenuItem {...otherProps} onPress={this.onPress} > {name} </MenuItem> ); } } AddNotificationPresetMenuItem.propTypes = { name: PropTypes.string.isRequired, implementation: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired }; export default AddNotificationPresetMenuItem;
src/pages/auth.js
voidxnull/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import ApiClient from '../api/client' import { API_HOST } from '../config'; import { ActionsTrigger } from '../triggers'; import { defaultSelector } from '../selectors'; import Footer from '../components/footer'; import Login from '../components/login'; import Register from '../components/register'; import Header from '../components/header'; import Messages from '../components/messages'; import Suggestions from './suggestions'; let FirstLogin = () => { return ( <div className="area"> <div className="area__body"> <div className="message"> <div className="message__body"> You are now successfully registered and logged in. You can proceed to <Link className="link" to="/induction">the next step</Link>. </div> </div> </div> </div> )}; let AuthForms = (props) => { return ( <div className="area"> <div> <div className="area__body layout-align_start"> <Login onLoginUser={props.triggers.login} /> <Register onRegisterUser={props.triggers.registerUser} /> </div> </div> </div> )}; let AuthContents = (props) => { let { current_user, is_logged_in, is_first_login, triggers, messages } = props; if(is_logged_in && !is_first_login){ return <Suggestions/>; } let content = <FirstLogin/>; if (!is_logged_in) { content = <AuthForms triggers={triggers}/>; } return ( <div> <Header is_logged_in={is_logged_in} current_user={current_user} /> <div className="page__body"> <Messages messages={messages} removeMessage={triggers.removeMessage} /> {content} </div> <Footer/> </div> ); }; class Auth extends React.Component { render() { let { current_user, is_logged_in, messages } = this.props; const client = new ApiClient(API_HOST); const triggers = new ActionsTrigger(client, this.props.dispatch); let is_first_login = false; if (current_user) { if (current_user.more) { is_first_login = current_user.more.first_login; } } return ( <AuthContents current_user={current_user} is_logged_in={is_logged_in} is_first_login={is_first_login} triggers={triggers} messages={messages} /> ) } } export default connect(defaultSelector)(Auth);