path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/containers/weather_list.js
swallville/React-ReduxExample
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; import GoogleMap from '../components/google_map'; class WeatherList extends Component { renderWeather(cityData){ const weat = cityData.list.map((data) => data.weather.map((rain) => rain.description)); const merged = [].concat.apply([], weat); const temps = cityData.list.map((weather) => [(weather.dt * 1000), parseFloat((weather.main.temp - 273.15).toFixed(2))]); const press = cityData.list.map((weather) => [(weather.dt * 1000), parseFloat(weather.main.pressure)]); const humi = cityData.list.map((weather) => [(weather.dt * 1000), parseFloat(weather.main.humidity)]); console.log(merged); const config_temp = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], isPureConfig: true, chart: { zoomType: 'x', backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, renderTo: 'container', borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, rangeSelector: { selected: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' }, text: `${cityData.city.name}'s Temperature` }, series: [{ name: 'Temperature (°C)', data: temps, tooltip: { crosshairs: true, shared: true, valueDecimals: 2 } }], subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle:{ color: 'gray' } }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, yAxis: { title: { text: 'Temperature (°C)' }, labels: { formatter: function () { return this.value + '°'; } } } }; const config_press = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], isPureConfig: true, chart: { zoomType: 'x', backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, renderTo: 'container', borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, rangeSelector: { selected: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' }, text: `${cityData.city.name}'s Pressure` }, series: [{ name: 'Pressure (hPa)', data: press, tooltip: { crosshairs: true, shared: true, valueDecimals: 2 } }], subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle:{ color: 'gray' } }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, yAxis: { title: { text: 'Pressure (hPa)' }, labels: { formatter: function () { return this.value + 'hPa'; } } } }; const config_humi = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], isPureConfig: true, chart: { zoomType: 'x', backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, renderTo: 'container', borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, rangeSelector: { selected: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' }, text: `${cityData.city.name}'s Humidity` }, series: [{ name: 'Humidity(%)', data: humi, tooltip: { crosshairs: true, shared: true, valueDecimals: 2 } }], subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle:{ color: 'gray' } }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, yAxis: { title: { text: 'Humidity (%)' }, labels: { formatter: function () { return this.value + '%'; } } }, }; return ( <tr key={cityData.city.id}> <td width={150} height={120}> <GoogleMap data={cityData.city.coord} /> </td> <td width={180} height={120}> <Chart config={config_temp} /> </td> <td width={180} height={120}> <Chart config={config_press} /> </td> <td width={180} height={120}> <Chart config={config_humi} /> </td> </tr> ); } render (){ return( <div className="table-responsive"> <table className="table table-striped table-bordered table-sm table-hover table-condensed"> <thead className="thead-default"> <tr> <th>City</th> <th>Temperature (°C)</th> <th>Pressure (hPa)</th> <th>Humidity (%)</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> </div> ); } } function mapStatetoProps( { weather } ) { return { weather }; } export default connect(mapStatetoProps)(WeatherList);
dashboard/app/actions/appActions.js
tlisonbee/cerberus-management-service
import React from 'react' import { hashHistory } from 'react-router' import axios from 'axios' import * as constants from '../constants/actions' import * as cms from '../constants/cms' import * as mSDBActions from '../actions/manageSafetyDepositBoxActions' import * as modalActions from '../actions/modalActions' import environmentService from 'EnvironmentService' import CreateSDBoxForm from '../components/CreateSDBoxForm/CreateSDBoxForm' import { initCreateNewSDB } from '../actions/createSDBoxActions' import ApiError from '../components/ApiError/ApiError' import * as messengerActions from '../actions/messengerActions' import { getLogger } from 'logger' var log = getLogger('application-actions') /** * Dispatch this action to let the app know that the sidebar data is being fetched */ export function fetchingSideBarData() { return { type: constants.FETCHING_SIDE_BAR_DATA } } /** * Dispatch this action to let the app know that the sidebar data has been fetched */ export function fetchedSideBarData(data) { return { type: constants.FETCHED_SIDE_BAR_DATA, payload: data } } export function fetchSideBarData(cerberusAuthToken) { return function(dispatch) { dispatch(fetchingSideBarData()) return axios.all([ axios.get(environmentService.getDomain() + cms.RETRIEVE_CATEGORY_PATH, { headers: { 'X-Cerberus-Token': cerberusAuthToken } }), axios.get(environmentService.getDomain() + cms.BUCKET_RESOURCE, { headers: { 'X-Cerberus-Token': cerberusAuthToken } }) ]) .then(axios.spread(function (categories, boxes) { log.debug("Received side bar data", categories, boxes) var data = {} for (var category of categories.data) { log.debug("parsing category", category) data[category.id] = { name: category.display_name, id: category.id, boxes: [] } } for (var box of boxes.data) { log.debug("parsing box", box) data[box.category_id]['boxes'].push({id: box.id, name: box.name, path: box.path}) } log.debug("Sidebar data", data) dispatch(fetchedSideBarData(data)) })) .catch(function (response) { log.error('Failed to fetch SideBar Data', response) dispatch(messengerActions.addNewMessage(<ApiError message="Failed to Fetch Side Bar Data" response={response} />)) }) } } export function fetchCmsDomainData(cerberusAuthToken) { return function(dispatch) { return axios.all([ axios.get(environmentService.getDomain() + cms.RETRIEVE_CATEGORY_PATH, { headers: { 'X-Cerberus-Token': cerberusAuthToken } }), axios.get(environmentService.getDomain() + cms.RETRIEVE_ROLE_PATH, { headers: { 'X-Cerberus-Token': cerberusAuthToken } }) ]) .then(axios.spread(function (categories, roles) { dispatch(storeCMSDomainData({categories: categories.data, roles: roles.data})) })) .catch(function (response) { log.error('Failed to fetch domain data', response) dispatch(messengerActions.addNewMessage(<ApiError message="Failed to Fetch CMS Domain Data" response={response} />)) }) } } export function storeCMSDomainData(data) { return { type: constants.STORE_DOMAIN_DATA, payload: data } } export function addBucketBtnClicked(categoryId) { return function(dispatch) { dispatch(initCreateNewSDB(categoryId)) dispatch(modalActions.pushModal(<CreateSDBoxForm />)) } } /** * Action for when a user clicks a safe deposit box in the sidebar or creates a safety deposit box * @param id The id of the safety deposit box * @param path The path for the safety deposit box * @param cerberusAuthToken The token needed for authenticated interaction with Cerberus */ export function loadManageSDBPage(id, path, cerberusAuthToken) { return function(dispatch) { dispatch(mSDBActions.updateNavigatedPath(path, cerberusAuthToken)) dispatch(mSDBActions.fetchSDBDataFromCMS(id, cerberusAuthToken)) hashHistory.push(`/manage-safe-deposit-box/${id}`) } } export function resetToInitialState() { return { type: constants.RESET_SIDEBAR_DATA } } /** * Action for loading version data into state */ export function loadDashboardMetadata() { return function(dispatch) { return axios({ url: '/dashboard/version', timeout: 10000 }) .then(function (response) { dispatch(storeDashboardMetadata(response.data)) }) .catch(function (response) { log.error(JSON.stringify(response, null, 2)) dispatch(modalActions.popModal()) dispatch(messengerActions.addNewMessage( <div className="login-error-msg-container"> <div className="login-error-msg-header">Failed to load dashboard metadata</div> <div className="login-error-msg-content-wrapper"> <div className="login-error-msg-label">Status Code:</div> <div className="login-error-msg-cms-msg">{response.status}</div> </div> </div> )) }) } } export function storeDashboardMetadata(data) { return { type: constants.STORE_DASHBOARD_METADATA, payload: { version: data.version } } }
src/components/Fridge.js
FrozenTear7/student-life-organizer
import React from 'react' import { connect } from 'react-redux' import { updateFridgeItem, fridgeItemResetEdit } from '../actions/fridgeActions' import renderField from './renderField' import { reduxForm, Field, reset } from 'redux-form' import {positiveNumber, required} from '../utils/validateForm' const submitFridgeItem = (values, dispatch, props) => { dispatch(updateFridgeItem(props.fridgeItem.id, values.text, values.amount)) dispatch(fridgeItemResetEdit()) dispatch(reset('Fridge')) } let Fridge = ({ handleSubmit, editedFridgeItem, fridgeItem, onFridgeItemEdit, onFridgeItemDelete, onFridgeItemGoBack }) => { if(fridgeItem.id !== editedFridgeItem.fridgeItem.id) { return ( <li className='list-group-item' key={fridgeItem.id} > <div className='container'> {fridgeItem.text} {fridgeItem.amount ? <div> Amount: {fridgeItem.amount} </div> : null } <button onClick={() => onFridgeItemEdit(fridgeItem)} className='btn btn-info btn-sm' > Edit </button> <button onClick={() => onFridgeItemDelete(fridgeItem.id)} className='btn btn-danger btn-sm' > Delete </button> </div> </li> ) } else { return ( <li className='list-group-item' key={fridgeItem.id}> <form onSubmit={handleSubmit(submitFridgeItem)} > <Field name='text' type='text' label='Edit Fridge Item' component={renderField} validate={required} /> <Field name='amount' type='number' label='Amount' component={renderField} validate={positiveNumber} /> <button type='submit' className='btn btn-success btn-sm' > Udpate Fridge Item </button> <button onClick={() => onFridgeItemGoBack()} className='btn btn-secondary btn-sm' > Go back </button> </form> </li> ) } } Fridge = reduxForm({ form: 'Fridge', enableReinitialize: true })(Fridge) Fridge = connect( state => ({ initialValues: state.fridge.editedFridgeItem.fridgeItem }) )(Fridge) export default Fridge
pages/api/paper.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './paper.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
src/view/components/ticket/TicketBook.js
Danny-Robinson/bt-bingo
import React from 'react'; import Ticket from './Ticket'; // const book = this.props.book // const { book } = this.props export default ({ book, cursor, colour }) => ( <div> { book.map((ticket, index) => <Ticket key={`ticket${index}`} name={`Ticket ${index + 1}`} rows={ticket} cursor={cursor} colour={colour}/>) } </div> ); // this.props.book.map(function (ticket) { // return <Ticket rows={ticket} /> // }) // const hey = () => {...}; // function hey () {...} // () => { return x } // () => (x) // () => x
src/containers/Example.js
WapGeaR/react-redux-boilerplate-auth
import React from 'react' import {BreadCrumbs, PageHeading} from 'template/layout' export default class Example extends React.Component { render() { return( <div className="page-content"> <BreadCrumbs childs={[ {name: 'Dashboard', url: '/'}, {name: 'Example page', last: true} ]}/> <PageHeading title="Example Page" /> <div className="container-fluid"> <div> <div className="row"> <div className="col-md-6 col-md-offset-5"> <h2>Example Page</h2> </div> </div> </div> </div> </div>) } }
js/react/es6-react/app.js
Pearyman/webexamples
import React from 'react'; class App extends React.Component { constructor(){ super(); this.state={ txt:'this is the state text', cat:0 } } update(e){ this.setState({txt: e.target.value}) } render() { return ( <div> <input type="text" onChange={this.update.bind(this)}/> <h1> {this.state.txt} </h1> </div>) } } module.exports= App;
techCurriculum/ui/solutions/4.7/src/components/CardForm.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; import TextInput from './TextInput.js' class CardForm extends React.Component { constructor(props) { super(props); this.state = {username: '', message: ''}; this.handleSubmit = this.handleSubmit.bind(this); this.handleUsernameChange = this.handleUsernameChange.bind(this); this.handleMessageChange = this.handleMessageChange.bind(this); } handleUsernameChange(value) { this.setState({username: value}); } handleMessageChange(value) { this.setState({message: value}); } handleSubmit(event) { } render() { return ( <form className='card-form'> <h2>Add a Card</h2> <TextInput name='username' label='Username' value={this.state.username} onChange={this.handleUsernameChange}/> <TextInput name='message' label='Message' value={this.state.message} onChange={this.handleMessageChange}/> <button className='btn btn-primary' onClick={this.handleSubmit}>Submit</button> </form> ); } } export default CardForm;
actor-apps/app-web/src/app/components/common/Banner.react.js
lstNull/actor-platform
import React from 'react'; import BannerActionCreators from 'actions/BannerActionCreators'; class Banner extends React.Component { constructor(props) { super(props); if (window.localStorage.getItem('banner_jump') === null) { BannerActionCreators.show(); } } onClose = () => { BannerActionCreators.hide(); }; onJump = (os) => { BannerActionCreators.jump(os); this.onClose(); }; render() { return ( <section className="banner"> <p> Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps! </p> <a className="banner__hide" onClick={this.onClose}> <i className="material-icons">close</i> </a> </section> ); } } export default Banner;
src/svg-icons/av/high-quality.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvHighQuality = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 11H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm7-1c0 .55-.45 1-1 1h-.75v1.5h-1.5V15H14c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v4zm-3.5-.5h2v-3h-2v3z"/> </SvgIcon> ); AvHighQuality = pure(AvHighQuality); AvHighQuality.displayName = 'AvHighQuality'; AvHighQuality.muiName = 'SvgIcon'; export default AvHighQuality;
client/desktop/app/components/teacher/classes/ClassData/LessonData.js
shanemcgraw/thumbroll
import React from 'react'; import api from '../../../../utils/api'; import moment from 'moment'; class LessonData extends React.Component { constructor(props){ super(props); this.state = { lessonId: this.props.params.lessonId, lessonName: this.props.location.state.lessonName, className: this.props.location.state.className, classId: this.props.location.state.classId, lessonDate: this.props.location.state.lessonDate, data: [], addThumbs: false, addMultiChoice: false, thumbsTitle: "", thumbsQuestion: "", multiTitle: "", multiQuestion: "", multiAnswer: "", multiA: "", multiB: "", multiC: "", multiD: "", formError: "" }; } render(){ const self = this; const lessonDate = new Date(this.state.lessonDate); const currentDay = new Date(); // wipe hours from dates, to compare days only. lessonDate.setHours(0,0,0,0); currentDay.setHours(0,0,0,0); const showButtons = lessonDate >= currentDay ? <div className='center-align'> <button className='newPollButton' onClick={this.handleAddThumbs.bind(self)}>Add thumbs check</button> <button className='newPollButton' onClick={this.handleAddMultiChoice.bind(self)}>Add multiple choice</button> </div> : <div></div>; var lessonIsInFuture = lessonDate >= currentDay; var showMCTable = this.state.data.filter(function(poll) { return poll.type === 'multiChoice'; }).length; var showThumbsTable = this.state.data.filter(function(poll){ return poll.type === 'thumbs'; }).length; console.log(showMCTable, showThumbsTable, lessonIsInFuture, 'should be true...'); const userMessage = () => { if(!showMCTable && !showThumbsTable) { if(lessonIsInFuture) { return 'No feedback is set to be recorded for this lesson. Add some below!'; } else { return 'No feedback has been recorded for this lesson.'; } } } return (<div> <h2 className='sectionHeading classList' onClick={this.handleClassClick.bind(this)}> <span className='pointer'>{this.state.className}</span> </h2> <h5 className='sectionHeading classList'>'{this.state.lessonName}'</h5> <div> <ThumbsTable data={this.state.data.filter(function(poll){ return poll.type === 'thumbs'; })} /> </div> <div> <MCTable data={this.state.data.filter(function(poll) { return poll.type === 'multiChoice'; })} /> </div> <div> <p style={{fontWeight: 400, marginBottom: '10px'}}> {userMessage()} </p> </div> {showButtons} <ErrorMessage className='center-align' formError={this.state.formError} /> <AddThumbsForm onSubmit={this.handleThumbsFormSubmit.bind(this)} lessonId={this.props.lessonId} addThumbs={this.state.addThumbs} thumbsTitle={this.state.thumbsTitle} thumbsQuestion={this.state.thumbsQuestion} handleThumbsTitleChange={this.handleThumbsTitleChange.bind(this)} handleThumbsQuestionChange={this.handleThumbsQuestionChange.bind(this)} /> <AddMultiChoiceForm onSubmit={this.handleMultiChoiceFormSubmit.bind(this)} lessonId={this.props.lessonId} addMultiChoice={this.state.addMultiChoice} multiTitle={this.state.multiTitle} multiQuestion={this.state.multiQuestion} multiAnswer={this.state.multiAnswer} multiA={this.state.multiA} multiB={this.state.multiB} multiC={this.state.multiC} multiD={this.state.multiD} handleMultiTitleChange={this.handleMultiTitleChange.bind(this)} handleMultiQuestionChange={this.handleMultiQuestionChange.bind(this)} handleMultiAnswerChange={this.handleMultiAnswerChange.bind(this)} handleMultiAChange={this.handleMultiAChange.bind(this)} handleMultiBChange={this.handleMultiBChange.bind(this)} handleMultiCChange={this.handleMultiCChange.bind(this)} handleMultiDChange={this.handleMultiDChange.bind(this)} /> </div>) } componentWillMount(){ api.getLessonPollsData(this.state.lessonId) .then((response) => { response.json().then((response) => { console.log('Individual lesson data from DB:', response); this.setState({ data:response }); }).catch((err) => { console.error(err); }); }) .catch((err) => { console.error(err); }); } handleClassClick() { this.context.router.push({ pathname: '/class/' + this.state.classId + '/lessons/', }); } handleAddThumbs(e) { // Pop out Thumbs form e.preventDefault(); this.setState({ addThumbs: true, addMultiChoice: false }); } handleAddMultiChoice(e) { // Pop out MultiChoice form e.preventDefault(); this.setState({ addThumbs: false, addMultiChoice: true }); } handleThumbsTitleChange(e) { this.setState({ thumbsTitle: e.target.value }); } handleThumbsQuestionChange(e) { this.setState({ thumbsQuestion: e.target.value }); } handleMultiTitleChange(e) { this.setState({ multiTitle: e.target.value }); } handleMultiQuestionChange(e) { this.setState({ multiQuestion: e.target.value }); } handleMultiAnswerChange(e) { this.setState({ multiAnswer: e.target.value }); } handleMultiAChange(e) { this.setState({ multiA: e.target.value }); } handleMultiBChange(e) { this.setState({ multiB: e.target.value }); } handleMultiCChange(e) { this.setState({ multiC: e.target.value }); } handleMultiDChange(e) { this.setState({ multiD: e.target.value }); } handleThumbsFormSubmit(e) { // Submit form data over API e.preventDefault(); console.log("Submit thumbs was clicked!") var lessonId = this.state.lessonId; var self = this; if (this.state.thumbsTitle && this.state.thumbsQuestion) { api.addThumbPoll(lessonId, this.state.thumbsTitle, this.state.thumbsQuestion) .then(function(response){ if (response) { console.log("POST RESPONSE: ", response); // Call API to grab new poll data api.getLessonPollsData(lessonId) .then((response) => { response.json().then((response) => { console.log('Individual lesson data from DB:', response); self.setState({ data:response }); }).catch((err) => { console.error(err); }); }) .catch((err) => { console.error(err); }); // Wipe relevant states self.setState({ thumbsTitle: "", thumbsQuestion: "" }); } else { console.log("POST ERROR") } }).catch(function(err){ console.log("ERROR POSTING: ", err); }); } else { // Mandatory fields not entered self.setState({ formError: "Please enter all required fields" }); console.log(self.state.formError); } } handleMultiChoiceFormSubmit(e) { // Submit form data over API e.preventDefault(); console.log("Submit thumbs was clicked!") var lessonId = this.state.lessonId; var self = this; if (this.state.multiTitle && this.state.multiQuestion && this.state.multiAnswer && this.state.multiA && this.state.multiB) { api.addMultiChoicePoll(lessonId, this.state.multiTitle, this.state.multiQuestion, this.state.multiAnswer, this.state.multiA, this.state.multiB, this.state.multiC, this.state.multiD) .then(function(response){ if (response) { console.log("POST RESPONSE: ", response); // Call API to grab new poll data api.getLessonPollsData(lessonId) .then((response) => { response.json().then((response) => { console.log('Individual lesson data from DB:', response); self.setState({ data:response }); }).catch((err) => { console.error(err); }); }) .catch((err) => { console.error(err); }); // add to state self.setState({ // Wipe relevant states multiTitle: "", multiQuestion: "", multiAnswer: "", multiA: "", multiB: "", multiC: "", multiD: "" }); } else { console.log("POST ERROR") } }).catch(function(err){ console.log("ERROR POSTING: ", err); }) } else { // Mandatory fields not entered self.setState({ formError: "Please enter all required fields" }); console.log("Please enter all required fields"); } } } const MCTable = (props) => { if(props.data.length) { return ( <div> <div className='tableContainer'> <table> <thead> <tr> <th> Multiple Choice Polls </th> <th> Response Count </th> <th> Accuracy Rate </th> </tr> </thead> <tbody> {props.data.map((poll) => { var correctRate = (poll.correct_response_count || 0) / poll.response_count * 100; return ( <tr key={'P' + poll.poll_id} > <td> {poll.poll_name || 'N/A'} </td> <td> {poll.response_count || 0} </td> <td> {!isNaN(correctRate) ? correctRate.toFixed(2) + '%' : 'N/A'} </td> </tr> ) })} </tbody> </table> </div> </div> ) } else { return ( <div></div> ) } } const ThumbsTable = (props) => { if(props.data.length) { return ( <div className='dataTable'> <div className='tableContainer'> <table> <thead> <tr> <th> Thumbs Checks </th> <th> Response Count </th> <th> Average Response </th> </tr> </thead> <tbody> {props.data.map((poll) => { return ( <tr key={'P' + poll.poll_id} > <td> {poll.poll_name || 'N/A'} </td> <td> {poll.response_count || 0} </td> <td> {poll.average_thumb ? poll.average_thumb.toFixed(2) + '%' : 'N/A'} </td> </tr> ) })} </tbody> </table> </div> </div> ) } else { return ( <div></div> ) } } const AddThumbsForm = (props) => { if (props.addThumbs) { return ( <div className='newPoll'> <h5 className='sectionHeading'>New Thumbs Check</h5> <form onSubmit={props.addStudent} className="pollForm"> <div> <input type='text' className='newPollInput' placeholder='Title (for your records)' maxLength={24} value={props.thumbsTitle} onChange={(event) => { props.handleThumbsTitleChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Question' value={props.thumbsQuestion} onChange={(event) => { props.handleThumbsQuestionChange(event); }} /> <text>*</text> </div> <div> <button onClick={props.onSubmit} style={{marginLeft:'0', fontSize: '1em'}} type='submit'>Add</button> </div> </form> </div> ) } else { return ( <div></div> ) } }; const AddMultiChoiceForm = (props) => { if (props.addMultiChoice) { return ( <div className='newPoll'> <h5 className='sectionHeading' >New Multiple Choice</h5> <form onSubmit={props.handleMultiChoiceFormSubmit} className="pollForm"> <div> <input type='text' className='newPollInput' placeholder='Short title (for your records)' value={props.multiTitle} maxLength={24} onChange={(event) => { props.handleMultiTitleChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Question' value={props.multiQuestion} onChange={(event) => { props.handleMultiQuestionChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Answer (A, B, C, or D)' value={props.multiAnswer} onChange={(event) => { props.handleMultiAnswerChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Option A' value={props.multiA} onChange={(event) => { props.handleMultiAChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Option B' value={props.multiB} onChange={(event) => { props.handleMultiBChange(event); }} /> <text>*</text> </div> <div> <input type='text' className='newPollInput' placeholder='Option C' value={props.multiC} onChange={(event) => { props.handleMultiCChange(event); }} /> </div> <div> <input type='text' className='newPollInput' placeholder='Option D' value={props.multiD} onChange={(event) => { props.handleMultiDChange(event); }} /> </div> <div> <button onClick={props.onSubmit} style={{marginLeft:'0', fontSize: '1em'}} type='submit'>Add</button> </div> </form> </div> ) } else { return ( <div></div> ) } }; const ErrorMessage = (props) => { if (props.formError) { return ( <div className='errorMessage'> {props.formError} </div> ) } else { return (<div></div>) } } LessonData.contextTypes = { router: React.PropTypes.any.isRequired }; module.exports = LessonData;
src/App.js
nickscaglione/frontend-articles-mic
import React, { Component } from 'react'; import './App.css'; import Table from './components/TableComponent' class App extends Component { render() { return ( <div className="App"> <Table /> </div> ); } } export default App;
src/svg-icons/action/assessment.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssessment = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/> </SvgIcon> ); ActionAssessment = pure(ActionAssessment); ActionAssessment.displayName = 'ActionAssessment'; ActionAssessment.muiName = 'SvgIcon'; export default ActionAssessment;
blueocean-material-icons/src/js/components/svg-icons/action/motorcycle.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionMotorcycle = (props) => ( <SvgIcon {...props}> <path d="M19.44 9.03L15.41 5H11v2h3.59l2 2H5c-2.8 0-5 2.2-5 5s2.2 5 5 5c2.46 0 4.45-1.69 4.9-4h1.65l2.77-2.77c-.21.54-.32 1.14-.32 1.77 0 2.8 2.2 5 5 5s5-2.2 5-5c0-2.65-1.97-4.77-4.56-4.97zM7.82 15C7.4 16.15 6.28 17 5 17c-1.63 0-3-1.37-3-3s1.37-3 3-3c1.28 0 2.4.85 2.82 2H5v2h2.82zM19 17c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/> </SvgIcon> ); ActionMotorcycle.displayName = 'ActionMotorcycle'; ActionMotorcycle.muiName = 'SvgIcon'; export default ActionMotorcycle;
examples/js/expandRow/manage-expanding.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i, expand: [ { fieldA: 'test1', fieldB: (i + 1) * 99, fieldC: (i + 1) * Math.random() * 100, fieldD: '123eedd' + i }, { fieldA: 'test2', fieldB: i * 99, fieldC: i * Math.random() * 100, fieldD: '123eedd' + i } ] }); } } addProducts(5); class BSTable extends React.Component { render() { if (this.props.data) { return ( <BootstrapTable data={ this.props.data }> <TableHeaderColumn dataField='fieldA' isKey={ true }>Field A</TableHeaderColumn> <TableHeaderColumn dataField='fieldB'>Field B</TableHeaderColumn> <TableHeaderColumn dataField='fieldC'>Field C</TableHeaderColumn> <TableHeaderColumn dataField='fieldD'>Field D</TableHeaderColumn> </BootstrapTable>); } else { return (<p>?</p>); } } } export default class ExpandRow extends React.Component { constructor(props) { super(props); this.handleExpand = this.handleExpand.bind(this); this.state = { // Default expanding row expanding: [ 2 ] }; } isExpandableRow() { return true; } handleExpand(rowKey, isExpand, e) { if (isExpand) { console.log(`row: ${rowKey} is ready to expand`); } else { console.log(`row: ${rowKey} is ready to collapse`); } console.log(e); } expandComponent(row) { return ( <BSTable data={ row.expand } /> ); } render() { const options = { expandRowBgColor: 'rgb(66, 134, 244)', expanding: this.state.expanding, onExpand: this.handleExpand }; return ( <BootstrapTable data={ products } options={ options } expandableRow={ this.isExpandableRow } expandComponent={ this.expandComponent } search> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' expandable={ false }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' expandable={ false }>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/docs/examples/PasswordInput/ExampleAllFeatures.js
StudentOfJS/ps-react-rod
import React from 'react'; import PasswordInput from 'ps-react-rod/PasswordInput'; /** All features enabled */ class ExampleAllFeatures extends React.Component { constructor(props) { super(props); this.state = { password: '' }; } getQuality() { const length = this.state.password.length; return length > 10 ? 100 : length * 10; } render() { return ( <div> <PasswordInput htmlId="password-input-example-all-features" name="password" onChange={ event => this.setState({ password: event.target.value })} value={this.state.password} minLength={8} placeholder="Enter password" showVisibilityToggle quality={this.getQuality()} {...this.props} /> </div> ) } } export default ExampleAllFeatures;
example/index.ios.js
AidenMontgomery/react-native-swiping-row
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, ListView, Text, View } from 'react-native'; import TableRow from 'react-native-swiping-row'; import Icon from 'react-native-vector-icons/FontAwesome'; export default class example extends Component { constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); const rows = []; rows.push({ icon: 'female', title: 'This is the title 1', subTitle: 'This is a subtitle 1' }); rows.push({ icon: 'space-shuttle', title: 'This is the title 2', subTitle: 'This is a subtitle 2' }); rows.push({ icon: 'handshake-o', title: 'This is the title 3', subTitle: 'This is a subtitle 3' }); rows.push({ icon: 'envelope', title: 'This is the title 4', subTitle: 'This is a subtitle 4' }); rows.push({ icon: 'heart', title: 'This is the title 5', subTitle: 'This is a subtitle 5' }); this.state = { dataSource: ds.cloneWithRows(rows), }; } render() { return ( <ListView dataSource={this.state.dataSource} renderRow={(rowData) => { let leftButtons = [{ defaultAction: false, fadeIn: true, text: 'Left 1', icon: <Icon name="thumbs-o-up" size={24} color={'white'} />, textStyle: { color: 'white' }, style: { backgroundColor: 'blue' }, onPress: () => { console.log('Left Button 1 Pressed') }, onLongPress: () => { console.log('Left Button 1 Long Press') } }, { defaultAction: true, fadeIn: true, renderOrder: 'icon', text: 'Left 2', icon: <Icon name="flag" size={24} color={'white'} />, textStyle: { color: 'white' }, style: { backgroundColor: 'green' }, onPress: () => { console.log('Left Button 2 Pressed') }, onLongPress: () => { console.log('Left Button 2 Long Press') } }]; let rightButtons = [{ defaultAction: true, fadeIn: true, renderOrder: 'text', icon: <Icon style={{ color: 'white', fontSize: 24 }} key='row-check' name={'trash'} />, text: 'Right 1', textStyle: { color: 'white' }, style: { backgroundColor: 'red' }, onPress: () => { console.log('Right Button 1 Pressed') }, onLongPress: () => { console.log('Right Button 1 Long Press') } }, { defaultAction: false, fadeIn: true, text: 'Right 2', renderOrder: 'icon', icon: <Icon style={{ color: 'white', fontSize: 24 }} name={'check'} />, textStyle: { color: 'white' }, style: { backgroundColor: 'purple' }, onPress: () => { console.log('Right Button 2 Pressed') }, onLongPress: () => { console.log('Right Button 2 Long Press') } }]; return ( <TableRow leftButtons={leftButtons} rightButtons={rightButtons} leftFullSwipeAction={() => console.log('Full swipe left on row ' + rowData)} rightFullSwipeAction={() => console.log('Full swipe right on row ' + rowData)} > <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20 }}> <Icon name={rowData.icon} style={{ color: 'white', width: 50 }} size={28} /> <View style={{ flexDirection: 'column', paddingHorizontal: 20, marginTop: 10 }}> <Text style={{ fontWeight: 'bold' }}>{rowData.title}</Text> <Text>{rowData.subTitle}</Text> </View> </View> </TableRow> ); }} /> ); } } AppRegistry.registerComponent('example', () => example);
newclient/scripts/components/admin/detail-view/admin-entities-summary/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. 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 styles from './style'; import React from 'react'; import EntitySummary from '../entity-summary'; import classNames from 'classnames'; export class AdminEntitiesSummary extends React.Component { constructor() { super(); this.getCommentCount = this.getCommentCount.bind(this); this.wasRespondedTo = this.wasRespondedTo.bind(this); } wasRespondedTo(id) { if (this.props.piResponses && Array.isArray(this.props.piResponses)) { return this.props.piResponses.some(response => { return response.targetId === id; }); } return false; } getCommentCount(id) { return this.props.comments.filter(comment => { return comment.topicId === id; }).length; } render() { let entities; if (Array.isArray(this.props.entities) && this.props.entities.length > 0) { entities = this.props.entities.filter(entity => { return entity.active === 1; }) .map((entity, index) => { return ( <EntitySummary key={`ent${entity.id}`} isLast={index === this.props.entities.length - 1} questions={this.props.questions} entity={entity} commentCount={this.getCommentCount(entity.id)} changedByPI={this.wasRespondedTo(entity.id)} /> ); }); } else { entities = ( <div className={styles.noEntities}>No active financial entities</div> ); } return ( <div className={classNames(styles.container, this.props.className)}> <div className={styles.heading}>FINANCIAL ENTITIES</div> <div className={styles.body}> {entities} </div> </div> ); } }
docs/src/sections/OverlaySection.js
mmarcant/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 OverlaySection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="custom-overlays">Custom overlays</Anchor> <small>Overlay</small> </h2> <p> The <code>OverlayTrigger</code> component is great for most use cases, but as a higher level abstraction it can lack the flexibility needed to build more nuanced or custom behaviors into your Overlay components. For these cases it can be helpful to forgo the trigger and use the <code>Overlay</code> component directly. </p> <ReactPlayground codeText={Samples.Overlay}/> <h4><Anchor id="custom-overlays-overlay">Use Overlay instead of Tooltip and Popover</Anchor></h4> <p> You don't need to use the provided <code>Tooltip</code> or <code>Popover</code> components. Creating custom overlays is as easy as wrapping some markup in an <code>Overlay</code> component </p> <ReactPlayground codeText={Samples.OverlayCustom} /> <h3><Anchor id="custom-overlays-props">Props</Anchor></h3> <PropTable component="Overlay"/> </div> ); }
client/src/routes/IndexPage.js
ZevenFang/react-meteor-todomvc
import React, { Component } from 'react'; import TodoItem from '../components/TodoItem'; import Meteor, {createContainer} from 'react-web-meteor'; let Todo = Meteor.collection('todo'); class IndexPage extends Component { constructor(props){ super(props); this.state = { filter: 'All' } } addTask = (text) => { Todo.insert({text, completed: false}); }; delTask = (id) => { Todo.remove(id); }; updTask = (id, text) => { Todo.update(id, {$set: {text}}); }; checkTask = (id, completed) => { Todo.update(id, {$set: {completed}}); }; clearCompleted = () => { let {todo} = this.props; todo.map(v=>( v.completed && Todo.remove(v._id) )); }; render(){ let {todo} = this.props; let completedTask = todo.filter(v=>!v.completed); let {filter} = this.state; if (filter==='Active') todo = todo.filter(v=>!v.completed); else if (filter==='Completed') todo = todo.filter(v=>v.completed); return ( <div> <section className="todoapp"> <Header onSubmit={this.addTask}/> {/* This section should be hidden by default and shown when there are todos */} <section className="main"> <input className="toggle-all" type="checkbox" /> <label htmlFor="toggle-all"> Mark all as complete </label> <ul className="todo-list"> {/* These are here just to show the structure of the list items */} {/* List items should get the class `editing` when editing and `completed` when marked as completed */} {todo.map((v,k)=>( <TodoItem key={k} todo={v} editTodo={this.updTask} deleteTodo={this.delTask} completeTodo={this.checkTask}/> ))} </ul> </section> {/* This footer should hidden by default and shown when there are todos */} <footer className="footer"> {/* This should be `0 items left` by default */} <span className="todo-count"><strong>{completedTask.length===0?'No':completedTask.length}</strong> item{completedTask.length>1?'s':''} left</span> {/* Remove this if you don't implement routing */} <ul className="filters"> <li onClick={() => this.setState({filter:'All'})}> <a className={filter==='All'?'selected':''} href="#">All</a> </li> <li onClick={() => this.setState({filter:'Active'})}> <a className={filter==='Active'?'selected':''} href="#">Active</a> </li> <li onClick={() => this.setState({filter:'Completed'})}> <a className={filter==='Completed'?'selected':''} href="#">Completed</a> </li> </ul> {/* Hidden if no completed items are left ↓ */} <button className="clear-completed" onClick={this.clearCompleted}> Clear completed </button> </footer> </section> <Footer/> </div> ); } } class Header extends Component { handleKeyPress = (e) => { if (e.key==='Enter'){ this.props.onSubmit(e.target.value); e.target.value = ''; } }; render(){ return ( <header className="header"> <h1>todos</h1> <input onKeyPress={this.handleKeyPress} className="new-todo" placeholder="What needs to be done?" autoFocus /> </header> ) } } class Footer extends Component { render(){ return ( <footer className="info"> <p> Double-click to edit a todo </p> {/* Remove the below line ↓ */} <p> Template by <a href="http://sindresorhus.com"> Sindre Sorhus </a> </p> {/* Change this out with your name and url ↓ */} <p> Created by <a href="https://github.com/zevenfang">Zeven Fang</a> </p> <p> Part of <a href="http://todomvc.com">TodoMVC</a> </p> </footer> ) } } export default createContainer(props=>{ Meteor.subscribe('todo'); let userId = Meteor.userId(); let todo = Todo.find({userId}, {sort: {createdAt: -1}}); return { todo } }, IndexPage);
src/shared/components/SelectInput/index.js
rvboris/finalytics
import React from 'react'; import Select from 'react-select'; import { defineMessages, injectIntl } from 'react-intl'; import './style.css'; const messages = defineMessages({ notFoud: { id: 'component.selectInput.notFound', description: 'Not found message', defaultMessage: 'Not found', }, }); const SelectInput = (props) => { const { intl, input, options } = props; const formatMessage = intl.formatMessage; const onChange = (event) => { if (input.onChange && event) { input.onChange(event.value); } }; const onBlur = () => { if (input.onBlur) { input.onBlur(input.value); } }; return ( <Select {...props} value={input.value || ''} onBlur={onBlur} onChange={onChange} options={options} noResultsText={formatMessage(messages.notFoud)} instanceId={input.name} /> ); }; SelectInput.propTypes = { intl: React.PropTypes.object.isRequired, input: React.PropTypes.object.isRequired, options: React.PropTypes.array.isRequired, }; export default injectIntl(SelectInput);
app/src/js/containers/action_buttons/ToggleDevToolsButton.js
Robert-Frampton/lexicon-customizer
import React from 'react'; import {connect} from 'react-redux'; import Button from '../../components/Button'; import {toggleDevTools} from '../../actions/preview'; const mapDispatchToProps = (dispatch, ownProps) => { return { onClick: (e) => { dispatch(toggleDevTools()); } }; }; const ToggleDevToolsButton = connect(null, mapDispatchToProps)(Button); export default ToggleDevToolsButton;
app/javascript/mastodon/features/ui/components/modal_root.js
masarakki/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Base from '../../../components/modal_root'; import BundleContainer from '../containers/bundle_container'; import BundleModalError from './bundle_modal_error'; import ModalLoading from './modal_loading'; import ActionsModal from './actions_modal'; import MediaModal from './media_modal'; import VideoModal from './video_modal'; import BoostModal from './boost_modal'; import ConfirmationModal from './confirmation_modal'; import FocalPointModal from './focal_point_modal'; import { OnboardingModal, MuteModal, ReportModal, EmbedModal, ListEditor, } from '../../../features/ui/util/async-components'; const MODAL_COMPONENTS = { 'MEDIA': () => Promise.resolve({ default: MediaModal }), 'ONBOARDING': OnboardingModal, 'VIDEO': () => Promise.resolve({ default: VideoModal }), 'BOOST': () => Promise.resolve({ default: BoostModal }), 'CONFIRM': () => Promise.resolve({ default: ConfirmationModal }), 'MUTE': MuteModal, 'REPORT': ReportModal, 'ACTIONS': () => Promise.resolve({ default: ActionsModal }), 'EMBED': EmbedModal, 'LIST_EDITOR': ListEditor, 'FOCAL_POINT': () => Promise.resolve({ default: FocalPointModal }), }; export default class ModalRoot extends React.PureComponent { static propTypes = { type: PropTypes.string, props: PropTypes.object, onClose: PropTypes.func.isRequired, }; getSnapshotBeforeUpdate () { return { visible: !!this.props.type }; } componentDidUpdate (prevProps, prevState, { visible }) { if (visible) { document.body.classList.add('with-modals--active'); } else { document.body.classList.remove('with-modals--active'); } } renderLoading = modalId => () => { return ['MEDIA', 'VIDEO', 'BOOST', 'CONFIRM', 'ACTIONS'].indexOf(modalId) === -1 ? <ModalLoading /> : null; } renderError = (props) => { const { onClose } = this.props; return <BundleModalError {...props} onClose={onClose} />; } render () { const { type, props, onClose } = this.props; const visible = !!type; return ( <Base onClose={onClose}> {visible && ( <BundleContainer fetchComponent={MODAL_COMPONENTS[type]} loading={this.renderLoading(type)} error={this.renderError} renderDelay={200}> {(SpecificComponent) => <SpecificComponent {...props} onClose={onClose} />} </BundleContainer> )} </Base> ); } }
src/svg-icons/file/create-new-folder.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCreateNewFolder = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"/> </SvgIcon> ); FileCreateNewFolder = pure(FileCreateNewFolder); FileCreateNewFolder.displayName = 'FileCreateNewFolder'; FileCreateNewFolder.muiName = 'SvgIcon'; export default FileCreateNewFolder;
wail-ui/loadingScreens/firstTime/containers/layout.js
N0taN3rd/wail
import React from 'react' import PropTypes from 'prop-types' import { namedPure } from '../../../util/recomposeHelpers' import Header from '../../shared/header' import { Card, CardHeader, CardMedia, CardText } from 'material-ui/Card' import ProgressSteps from '../components/progress/progressSteps' import ProgressMessage from '../components/progress/progressMessage' import { firstTimeLoading } from '../../../constants/uiStrings' const enhance = namedPure('Layout') function Layout () { return [ <Header key='firsttime-layout-header' title={firstTimeLoading.title} />, <div key='firsttime-layout-contentBody' style={{ transform: 'translateY(10px)' }} > <div className='wail-container'> <Card style={{ minHeight: '350px' }}> <CardHeader title={firstTimeLoading.autoConfigSteps} /> <CardMedia style={{ minHeight: '300px' }}> <ProgressSteps/> <ProgressMessage/> </CardMedia> </Card> </div> </div> ] } export default enhance(Layout)
src/apps/storefront/src/components/header/index.js
Kevnz/shopkeep
import React, { Component } from 'react'; class Header extends Component { render() { return ( <div> <header> <a href="#" className="logo">Shopkeep</a> <button>Home</button> <span>|</span> <button>About</button> <button>Contact</button> <button>Cart</button> </header> </div> ); } } export default Header;
docs/src/components/Header/Header.js
bmatthews/haze-lea
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import Logo from './haze-lea-logo.svg'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Link className={s.brand} to="/"> <img className={s.logo} src={Logo} /> </Link> </div> </div> ); } } export default withStyles(s)(Header);
src/client/Spinner.js
JiLiZART/tmfeed-menu
import React from 'react' export default class Spinner extends React.Component { render () { return ( <div className='spinner'> Загрузка... </div> ) } }
src/Facts.js
RafaelCosman/alchemistsSolver
import _ from 'lodash' import React from 'react' import {Text} from 'react-native' import {potions, potionsInverted, ingredients, alchemicals, correctnessOpts} from './Enums.js' import {MyIcon} from './MyIcon.js' import {mixInWorld} from './Logic.js' class Fact { updatePrior(weightedWorld) { throw new Error("updatePrior not defined for this fact type") } mentionedIngredients() { throw new Error("mentionedIngredients not defined for this fact type") } } ////////////////////// // Specific Fact types: ////////////////////// class GolemTestFact extends Fact { constructor(ingredient, effects) { super() this.ingredient = ingredient this.effects = effects } updatePrior = (weightedWorld) => { const alchemical = alchemicals[weightedWorld.ingAlcMap[this.ingredient]] const sizes = [0,0,0] for (let i = 0; i < 3; i++) { sizes[i] = alchemical[i] === alchemical[(i+1) % 3] ? 1 : -1 } weightedWorld.golemMaps = _.filter(weightedWorld.golemMaps, (golemMap) => { for (let aspect = 0; aspect < 3; aspect++) { const effect = golemMap[aspect] if (effect === 'nothing') { continue } const effectIndex = _.findIndex(['ears', 'chest'], (value) => value === effect.affects) if ((effect.size === sizes[aspect]) !== this.effects[effectIndex]) { return false } } return true }) } mentionedIngredients = () => [this.ingredient] render = () => { return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredient]}/> <Text>→</Text> <MyIcon imageDir='golemTest' name={this.effects.join('')}/> </> } } class GolemAnimationFact extends Fact { constructor(ingredients, success) { super() this.ingredients = ingredients this.success = success } updatePrior = (weightedWorld) => { const alchemical0 = alchemicals[weightedWorld.ingAlcMap[this.ingredients[0]]] const alchemical1 = alchemicals[weightedWorld.ingAlcMap[this.ingredients[1]]] const aspects = _.zipWith(alchemical0, alchemical1, (a, b) => (a+b)/2) weightedWorld.golemMaps = _.filter(weightedWorld.golemMaps, (golemMap) => { const worldAspects = _.map(golemMap, (affect) => { if (affect === 'nothing') { return 0 } else { return affect.size } }) return this.success === _.isEqual(aspects, worldAspects) }) } mentionedIngredients = () => this.ingredients render = () => { return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredients[0]]}/> <Text>+</Text> <MyIcon imageDir='ingredients' name={ingredients[this.ingredients[1]]}/> {this.success ? "animates the golem!" : "fails to animate the golem"} </> } } class LibraryFact extends Fact { constructor(ingredient, isSolar) { super() this.ingredient = ingredient this.isSolar = isSolar } updatePrior = (weightedWorld) => { const world = weightedWorld.ingAlcMap const alchemical = alchemicals[world[this.ingredient]] const isSolar = _.filter(alchemical, (value) => (value === -1)).length % 2 === 0 if (isSolar !== this.isSolar) { weightedWorld.multiplicity = 0 } } mentionedIngredients = () => [this.ingredient] render = () => { return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredient]}/> <Text>∈</Text> {<MyIcon imageDir="classes" name={this.isSolar ? "solar" : "lunar"}/>} </> } } // This is what a set of aspects looks like: // [[1,0,0], [0,0,-1]] is red+ or blue- class OneIngredientFact extends Fact { constructor(ingredient, setOfAspects, bayesMode) { super() this.ingredient = ingredient this.setOfAspects = setOfAspects this.bayesMode = bayesMode } updatePrior = (weightedWorld) => { const world = weightedWorld.ingAlcMap const alchemical = alchemicals[world[this.ingredient]] let likelihoodFactor = 0 for (let aspectIndex = 0; aspectIndex < this.setOfAspects.length; aspectIndex++) { if (this.setOfAspects[aspectIndex]) { const aspect = _.values(potions)[aspectIndex] for (let color = 0; color < 3; color++) { if (aspect[color] === alchemical[color]) { if (this.bayesMode) { likelihoodFactor += 1 } else { return //The world is possible, so don't change anything } } } } } weightedWorld.multiplicity *= likelihoodFactor } mentionedIngredients = () => [this.ingredient] render = () => { const aspectNames = _.filter(_.keys(potions), (name, index) => this.setOfAspects[index]) const imageDir = this.bayesMode ? "potions" : "aspects" let text = this.bayesMode ? "made" : "has" if (aspectNames.length !== 1) { text += " at least one of" } return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredient]}/> <Text>{text}</Text> {aspectNames.map((name, index) => <MyIcon imageDir={imageDir} name={name} key={index}/>)} </> } } class TwoIngredientFact extends Fact { constructor(ingredients, possibleResults) { super() this.ingredients = ingredients this.possibleResults = possibleResults } // This function is in the inner loop and so we're optimizing it updatePrior = (weightedWorld) => { const result = mixInWorld(weightedWorld, this.ingredients) const potionIndex = potionsInverted["" + result] weightedWorld.multiplicity *= this.possibleResults[potionIndex] } mentionedIngredients = () => this.ingredients render = () => { const numTrue = _.filter(this.possibleResults).length let potionNames = _.keys(potions) if (numTrue === potionNames.length - 1) { const potionName = potionNames[_.findIndex(this.possibleResults, _.negate(_.identity))] return this.showFact('≠', [potionName]) } potionNames = _.filter(potionNames, (name, index) => { return this.possibleResults[index] }) if (potionNames.length === 1 || _.every(potionNames, function(name) {return name.indexOf('+') !== -1}) || _.every(potionNames, function(name) {return name.indexOf('-') !== -1})) { return this.showFact('=', [potionNames.join("")]) } return this.showFact('∈', potionNames) } showFact = (seperator, potionList) => { return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredients[0]]}/> <Text>+</Text> <MyIcon imageDir='ingredients' name={ingredients[this.ingredients[1]]}/> <Text>{seperator}</Text> {potionList.map((name, index) => <MyIcon imageDir='potions' name={name} key={index}/>)} </> } } class RivalPublicationFact extends Fact { constructor(ingredient, alchemical, odds) { super() this.ingredient = ingredient this.alchemical = alchemical this.odds = odds } updatePrior = (weightedWorld) => { const actualAlchemical = weightedWorld.ingAlcMap[this.ingredient] const diff = _.zipWith(alchemicals[this.alchemical], alchemicals[actualAlchemical], (a, b) => a === b) const i = _.findIndex(_.values(correctnessOpts), x => _.isEqual(x, diff)) weightedWorld.multiplicity *= this.odds[i] } mentionedIngredients = () => [this.ingredient] render = () => { return <> <MyIcon imageDir='ingredients' name={ingredients[this.ingredient]}/> <Text>was published as</Text> <MyIcon imageDir='alchemicals' name={alchemicals[this.alchemical].join("")}/> ({_.map(this.odds, (value, key) => value).join(",")}) </> } } export {GolemTestFact, GolemAnimationFact, LibraryFact, OneIngredientFact, TwoIngredientFact, RivalPublicationFact}
app/javascript/components/ui/LoadingSpinner.js
avalonmediasystem/avalon
/* * Copyright 2011-2022, The Trustees of Indiana University and Northwestern * University. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * --- END LICENSE_HEADER BLOCK --- */ import React from 'react'; const LoadingSpinner = ({ isLoading }) => isLoading ? <div className="loading-spinner" /> : null; export default LoadingSpinner;
client/src/Components/oldMasterForm/WorkPrefs.js
teamcrux/EmploymentOptions
import React from 'react'; import { Field } from 'redux-form'; const WorkPrefs = () => { return ( <div className="section"> <div> <label htmlFor="fulltime">Full time</label> <Field name="fulltime" id="fulltime" component="input" type="checkbox"/> <label htmlFor="parttime">Part time</label> <Field name="parttime" id="parttime" component="input" type="checkbox"/> </div> <div> <label htmlFor="num_hours"> How many hours?</label> <Field name="num_hours" component="input" type="text"/> </div> <div> <label htmlFor="expected_wage">Expected wage</label> <Field name="expected_wage" component="input" type="text"/> </div> <div className="days"> <label>What days of the week? &nbsp;</label> <label htmlFor="monday"> M</label> <Field name="monday" id="monday" component="input" type="checkbox"/> <label htmlFor="tuesday"> T</label> <Field name="tuesday" id="tuesday" component="input" type="checkbox"/> <label htmlFor="wednesday"> W</label> <Field name="wednesday" id="wednesday" component="input" type="checkbox"/> <label htmlFor="thursday"> Th</label> <Field name="thursday" id="thursday" component="input" type="checkbox"/> <label htmlFor="friday"> F</label> <Field name="friday" id="friday" component="input" type="checkbox"/> <label htmlFor="saturday"> S</label> <Field name="saturday" id="saturday" component="input" type="checkbox"/> <label htmlFor="sunday"> Su</label> <Field name="sunday" id="sunday" component="input" type="checkbox"/> </div> <div className="hours"> <label>What hours?&nbsp;&nbsp;</label> <label htmlFor="hours_days">&nbsp;Days </label> <Field name="hours_days" id="hours_days" component="input" type="checkbox"/> <label htmlFor="hours_swing">&nbsp;Swing </label> <Field name="hours_swing" id="hours_swing" component="input" type="checkbox"/> <label htmlFor="hours_noc">&nbsp;NOC</label> <Field name="hours_noc" id="hours_noc" component="input" type="checkbox"/> </div> <div className="inside-outside"> <label>Where would you prefer to work?&nbsp;</label> <label htmlFor="inside">&nbsp;Inside</label> <Field name="inside" id="inside" component="input" type="checkbox"/> <label htmlFor="outside">&nbsp;Outside</label> <Field name="outside" id="outside" component="input" type="checkbox"/> </div> <div> <label htmlFor="geo_pref">Preferred geographical area</label> <Field name="geo_pref" component="input" type="text"/> </div> </div> ) } export default WorkPrefs
opwen_statuspage/src/PingStats.js
ascoderu/opwen-cloudserver
import React from 'react'; import PropTypes from 'prop-types'; import { Card, Icon, List, Statistic, notification } from 'antd'; import axios from 'axios'; import Grid from './Grid'; const colors = { success: '#3f8600', failure: '#cf1322', }; class PingStat extends React.Component { state = { pingTimeMillis: undefined, pingSuccess: undefined, }; _pingInterval = undefined; _onPing = async () => { const { serverEndpoint } = this.props; const pingStart = new Date().getTime(); let pingSuccess; try { await axios.get(serverEndpoint); pingSuccess = true; } catch (e) { notification.error({ message: 'Unable to ping server', description: (e.response && e.response.data) || e.message, }); pingSuccess = false; } this.setState({ pingTimeMillis: new Date().getTime() - pingStart, pingSuccess, }); }; async componentDidMount() { const { pingIntervalSeconds } = this.props; await this._onPing(); this._pingInterval = setInterval(this._onPing, pingIntervalSeconds * 1000); } componentWillUnmount() { if (this._pingInterval != null) { clearInterval(this._pingInterval); } } render() { const { title } = this.props; const { pingSuccess, pingTimeMillis } = this.state; return ( <List.Item key={title}> <Card> <Statistic title={title} value={pingTimeMillis} suffix="ms" prefix={<Icon type={pingSuccess ? 'check' : 'warning'} />} valueStyle={{ color: pingSuccess ? colors.success : colors.failure, }} /> </Card> </List.Item> ); } } PingStat.propTypes = { title: PropTypes.string.isRequired, serverEndpoint: PropTypes.string.isRequired, pingIntervalSeconds: PropTypes.number.isRequired, }; function PingStats(props) { const { serverEndpoint, pingIntervalSeconds } = props.settings; return ( <Grid> <PingStat title="Server ping" pingIntervalSeconds={pingIntervalSeconds} serverEndpoint={`${serverEndpoint}/healthcheck/ping`} /> <PingStat title="Webapp ping" pingIntervalSeconds={pingIntervalSeconds} serverEndpoint={`${serverEndpoint}/web/healthcheck/ping`} /> </Grid> ); } PingStats.propTypes = { settings: PropTypes.shape({ pingIntervalSeconds: PropTypes.number.isRequired, serverEndpoint: PropTypes.string.isRequired, }).isRequired, }; export default PingStats;
tests/react_children/view.js
MichaelDeBoey/flow
// @flow import React from 'react'; type ReactNodeWithoutString = | void | null | boolean | React$Element<any> | Array<ReactNodeWithoutString>; // NOTE: This is intentionally `Array<T>` and // not `Iterable<T>` because `strings` are // `Iterable<string>` which is then // `Iterable<Iterable<string>>` recursively // making strings valid children when we use // `Iterable<T>`. class View extends React.Component<{children: ReactNodeWithoutString}, void> {} // OK: Allows any non-string children. <View> {} {undefined} {null} {true} {false} <buz /> {[undefined, null, true, false, <buz />]} </View>; // Error: Arbitrary objects are not allowed as children. <View> {{a: 1, b: 2, c: 3}} </View>; <View>Hello, world!</View>; // Error: Strings are not allowed as children. <View>{'Hello, world!'}</View>; // Error: Strings are not allowed as children. <View>{42}</View>; // Error: Numbers are not allowed as children. <View>{1}{2}{3}</View>; // Error: Numbers are not allowed as children. <View>{['a', 'b', 'c']}</View>; // Error: Strings are not allowed deeply. <View>{[1, 2, 3]}</View>; // Error: Numbers are not allowed deeply.
modules/indexableFolder/client/routes/indexableFolder.client.menu.js
dimitriaguera/playlist-app
/** * Created by Dimitri Aguera on 21/09/2017. */ import React from 'react'; import { NavLink } from 'react-router-dom'; export const menuItems = [ { component: () => ( <NavLink to="/music" activeClassName="nav-selected"> Folder </NavLink> ), menuId: 'main' } ];
fields/types/email/EmailColumn.js
vokal/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var EmailColumn = React.createClass({ displayName: 'EmailColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value) return; return ( <ItemsTableValue to={'mailto:' + value} padded exterior field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = EmailColumn;
src/svg-icons/navigation/more-vert.js
nathanmarks/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;
app/utils/injectReducer.js
ninjaref/ninjaref
import React from 'react'; import PropTypes from 'prop-types'; import hoistNonReactStatics from 'hoist-non-react-statics'; import getInjectors from './reducerInjectors'; /** * Dynamically injects a reducer * * @param {string} key A key of the reducer * @param {function} reducer A reducer that will be injected * */ export default ({ key, reducer }) => (WrappedComponent) => { class ReducerInjector extends React.Component { static WrappedComponent = WrappedComponent; static contextTypes = { store: PropTypes.object.isRequired, }; static displayName = `withReducer(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`; componentWillMount() { const { injectReducer } = this.injectors; injectReducer(key, reducer); } injectors = getInjectors(this.context.store); render() { return <WrappedComponent {...this.props} />; } } return hoistNonReactStatics(ReducerInjector, WrappedComponent); };
src/components/App.js
Plop3D/sandbox
import React from 'react' import ReactDOM from 'react-dom' import {injectGlobal} from 'styled-components' import { Lights, Sky, VRScene, LeftController, RightController, Fingers, Camera, Primitives, LoginBox, Shapes } from 'components' class App extends React.Component { constructor(props) { super(props) window.emit = (type, data) => { if (type === 'grab:start') { this.lastGrab = data // Fingers are positioned inside camera and we need to adjust a finger // Coordinate to the world var cameraNode = ReactDOM.findDOMNode(this.refs.camera) const point = cameraNode.object3D .localToWorld(new THREE.Vector3(data.x, data.y, data.z)) // Go over all shapes and check if the grab happenned inside one of them // We check shapes first to allow them to move away from the primitives this.refs.shapes.getShapes().forEach((shape) => { if (shape.wasMounted()){ const box = new THREE.Box3().setFromObject(ReactDOM.findDOMNode(shape).object3D) if (box.containsPoint(point)){ this.selectedShape = shape return } } }) // If we grab outside of the shapes, go over primitives and create a // Shape and select it for daggin this.refs.primitives.getPrimitives().forEach((primitive) => { const box = new THREE.Box3().setFromObject(ReactDOM.findDOMNode(primitive).object3D) if (box.containsPoint(point)){ this.selectedShape = this.refs.shapes.addShape(primitive) return } }) } else if (type === 'grab:end') { this.lastGrab = this.selectedShape = null } else if (type === 'grab:move') { if (this.selectedShape && this.selectedShape.wasMounted()){ this.selectedShape.move(data, this.lastGrab) this.lastGrab = data } } } } componentDidMount() { injectGlobal` body { margin: 0; } .a-canvas { position: relative; } ` } render() { return ( <div> <iframe src="/video" style={{ position: "absolute", left: 0, top: 0, width: 240 + 'px', height: 180 + 'px', zIndex: 9999 }} frameBorder="0"/> <VRScene> <LoginBox/> <LeftController /> <RightController /> <Sky /> <Lights /> <Camera ref='camera'><Fingers /></Camera> <Primitives ref='primitives' /> <Shapes ref='shapes' /> </VRScene> </div> ) } } export default App
react-fundamentals-es6/lessons/14-build-compiler/main.js
3mundi/React-Bible
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
test/regressions/tests/Menu/LongMenu.js
lgollut/material-ui
import React from 'react'; import IconButton from '@material-ui/core/IconButton'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import MoreVertIcon from '@material-ui/icons/MoreVert'; const styles = { root: { margin: '200px 0 200px', background: 'papayawhip', padding: '0 100px', }, }; const options = [ 'None', 'Atria', 'Callisto', 'Dione', 'Ganymede', 'Hangouts Call', 'Luna', 'Oberon', 'Phobos', 'Pyxis', 'Sedna', 'Titania', 'Triton', 'Umbriel', ]; const ITEM_HEIGHT = 48; class LongMenu extends React.Component { buttonRef = React.createRef(); state = { anchorEl: null, }; componentDidMount() { this.setState({ anchorEl: this.buttonRef.current }); } render() { const { classes } = this.props; const { anchorEl } = this.state; const open = Boolean(anchorEl); return ( <div className={classes.root}> <IconButton ref={this.buttonRef} aria-label="more" aria-owns={open ? 'long-menu' : undefined} aria-haspopup="true" onClick={this.handleClick} > <MoreVertIcon /> </IconButton> <Menu id="long-menu" anchorEl={anchorEl} open={open} PaperProps={{ style: { maxHeight: ITEM_HEIGHT * 4.5, width: 200, }, }} > {options.map((option) => ( <MenuItem key={option} selected={option === 'Pyxis'}> {option} </MenuItem> ))} </Menu> </div> ); } } LongMenu.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(LongMenu);
js/components/pages/HomePage.react.js
wuyuanyi135/react-template
/* * HomePage * This is the first thing users see of our App */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Grid, Row, Col } from 'react-bootstrap'; import RecentImport from '../components/RecentImport.react.js'; import RecentApplicant from '../components/RecentApplicant.react.js'; import SearchBar from '../components/SearchBar.react.js'; import DetailDialog from '../components/DetailDialog.react.js'; import * as homeActions from '../../actions/AppActions.js'; import * as indexActions from '../../actions/IndexActions.js'; import * as importActions from '../../actions/ImportFormActions.js'; class HomePage extends Component { componentDidMount() { this.props.dispatch(homeActions.fetchRecent(false)); } render() { const dispatch = this.props.dispatch; const show = this.props.show; return ( <div> <h1>搜索</h1> <SearchBar onSelect={(arg) => dispatch(indexActions.displayArticleDialog(arg.suggestion.original._id))}/> <Grid fluid> <Row> <Col md={4}> <RecentImport /> </Col> <Col md={4}> <RecentApplicant /> </Col> <Col md={4}> </Col> </Row> </Grid> {show ? <DetailDialog /> : null} </div> ); } } function select(state) { return { show: state.home.displayDialog }; } // Wrap the component to inject dispatch and state into it export default connect(select)(HomePage);
src/pages/index.js
thijsvdv/gatsby-test
import React from 'react' import { compose } from "recompose" import { withScriptjs, withGoogleMap, GoogleMap, Marker, } from "react-google-maps" // import Link from 'gatsby-link' import styled from 'styled-components' import Contact from './form' // import Execution from './slides/execution' // import Focus from './slides/focus' // import { Wrapper, Background, Slice, Triple, H2, H3, H4, Tag, Visual, Visual1, Quote, Author, Clients, Client, Face } from './components' const logos = [ { url: require('./clients/1.png'), style: {} }, { url: require('./clients/2.png'), style: { maxWidth: '100px' } }, { url: require('./clients/3.png'), style: {} }, { url: require('./clients/4.png'), style: {} }, { url: require('./clients/5.png'), style: {} }, { url: require('./clients/6.png'), style: {} }, { url: require('./clients/7.jpg'), style: { maxWidth: '200px', maxHeight: '130px' } }, { url: require('./clients/8.jpg'), style: {} }, { url: require('./clients/9.jpg'), style: {} }, { url: require('./clients/10.png'), style: {} }, { url: require('./clients/11.png'), style: {} }, { url: require('./clients/12.png'), style: {} } ] export default class IndexPage extends React.Component { constructor (props) { super(props) this.state = { visibility: [0, 0, 0, 0, 0, 0] } this.sections = [] } componentDidMount () { } toggleContent = (e, index) => { e.persist() this.setState(prevState => { const visibility = new Array(6).fill(false) visibility[index] = !prevState.visibility[index] return { visibility } }) setTimeout(() => { typeof window !== 'undefined' && window.scrollBy({ top: e.target.getBoundingClientRect().top - 58, left: 0, behavior: 'smooth' }) }, 500) } render () { return ( <Wrapper> <Slice id='execution' name='execution'> <H2>Execution</H2> <p>Are your people, processes or systems struggling to keep up with changes in the marketplace?</p> <p>Do you need dramatic performance improvements to address customer requirements, competitive pressures, or shareholder expectations?</p> <p>Are your process improvement initiatives not delivering the expected returns?</p> <p>Are you struggling to manage change and make improvements stick?</p> <p>Are you lacking the internal bandwidth to properly manage a complex or high-risk project with focus, accountability, and results?</p> <p>Could an outside perspective or more methodical approach be helpful in addressing and solving some challenging and persistent problem once and for all?</p> <H4>Could speed and quality of execution be the differentiator needed to set your company apart?</H4> </Slice> <Background large> <Visual src={require('./visuals/2. The Execution Challenge.png')} style={{ width: '100%', height: 'auto', margin: '20px 0 0', maxWidth: '600px' }} /> </Background> <Slice id='services'> <H2>Services</H2> <p>Execution Partners helps companies improve performance & achieve objectives through focused execution support, and the implementation of efficient and reliable "execution systems"</p> <p>We partner with our clients to solve their most challenging problems, streamline critical processes, and execute complex projects and programs, while carefully managing change and building internal capabilities.</p> <p>We provide expert guidance, best practices, effective tools, and hands-on support, enabling teams to achieve better results faster, cheaper, and more sustainably through improved clarity, alignment, transparency and accountability.</p> <p>Wherever possible, we strive to implement efficient and reliable “execution systems” to enable significant and sustainable performance improvement, through the alignment of people, processes, and technology.</p> <H4>Execution Partners - your shortest and surest path from challenges to results.</H4> </Slice> <Background large id='focus'> <Overflow> <Visual src={require('./visuals/3. PRO3 Execution Systems.png')} style={{ width: '100%', height: 'auto', margin: 0, maxWidth: '800px' }} /> </Overflow> </Background> <Slice> <H2>Focus</H2> <div style={{ marginTop: '-20px' }}> <AccordeonTitle open={this.state.visibility[0]} onClick={(e) => this.toggleContent(e, 0)} ref={section => { this.sections[0] = section }} >Project Management</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[0]}> <p>Projects are a part of life in business. They’re a powerful approach to help us get from where we are to where we need to be. Sound project management can deliver the desired results in the shortest time and most efficient way. Unfortunately, due to the temporary nature, wide range of challenges, and day-to-day operational responsibilities and priorities, many companies struggle to execute projects consistently. As a result, projects tend to place a heavy burden on an organization, taking up too much time and resources, dragging on for too long, and often ending up dying a silent death - or failing even more painfully.</p> <p>Execution Partners can provide expert advice, best practices, tools, training, and coaching, but can also take a more direct role, from providing basic project management support, to taking the lead in the overall end-to-end project management. Using our proven methodology and powerful tools, we have supported projects large and small, addressing many different challenges, in very different industries, ranging from construction project management to systems implementation to strategy execution.</p> <p>Applying our unique methodology, we assist our clients in achieving improved clarity and alignment on purpose, objectives, and approach. We implement and help sustain better project structure and coordination, and unlock the focus and accountability necessary to deliver the desired progress and results. Through expert coaching, hands-on support, or full-blown project leadership, we help deliver projects on time, complete, according to specifications, and -most importantly- with the expected results and return on investment.</p> </AccordeonContent> </AccordeonWrapper> <AccordeonTitle open={this.state.visibility[1]} onClick={(e) => this.toggleContent(e, 1)} ref={section => { this.sections[1] = section }} >Process Improvement</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[1]}> <p>In essence, companies represent a collection of business processes that create and deliver value to their customers. Unfortunately, processes have a tendency to deteriorate and increase in complexity over time. For that reason, it is essential to keep maintaining and improving especially those processes most important to the customer experience, and those processes most critical to an organization’s overall competitiveness and profitability.</p> <p>Execution Partners can help identify and prioritize the processes most in need of improvement. We can help measure current performance levels, define realistic performance targets, and assess the dollar value of improved performance. Together with our client’s team of subject matter experts, we can map out and visualize the process in as much detail as needed, including any interfaces, hand-offs, and system support involved.</p> <p>Effective process mapping allows us to identify and assess obstacles, inefficiencies, and vulnerabilities. Based on a clear understanding of customer expectations, stakeholder concerns, and the broader context of related processes and systems, we can then develop and implement a focused action plan for improvement, in order to streamline the process, address any waste and vulnerabilities, improve system support, and achieve the desired improvements in performance.</p> <p>Finally, implementing proper process controls and feedback loops, defining clear roles and responsibilities, and paying special attention to proper change management practices, all help to ensure optimal adoption and sustainable results.</p> </AccordeonContent> </AccordeonWrapper> <AccordeonTitle open={this.state.visibility[2]} onClick={(e) => this.toggleContent(e, 2)} ref={section => { this.sections[2] = section }} >Problem Solving</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[2]}> <p>Effective problem solving is critical for every organization. Improving processes, managing projects, and simply running the day-to-day operations, would all be impossible without continuous problem solving. Problems come in many different shapes and sizes, including issues, risks, and opportunities of different types and levels of complexity. Whether we are trying to resolve an actual issue, mitigate a risk, or leverage an opportunity, it’s important to use an appropriate problem solving approach.</p> <p>There are many different problem solving strategies, methodologies and techniques, ranging from very simple to rather sophisticated. Execution Partners helps its clients select and apply the right problem solving approach for the specific challenge being addressed. More often than not, simple is better, and a touch of human ingenuity beats statistical analyses. Essential is to clearly define the problem, agree on the objectives and success metrics, understand the cause-effect relationships, develop and assess a range of feasible options, and lay out a practical action plan. We can provide effective facilitation, bringing together a balanced set of stakeholders and subject matter experts, creating a productive environment, and asking focused questions. By using the Socratic approach, scientific method, and design thinking techniques, we stimulate creative thinking and organizational learning.</p> <p>Execution Partners can provide a fresh, outside perspective, help a team look at things from new angles, and bring ideas from different industries and environments. Of course, problem solving -for all but the simplest problems- should lead to action planning, and be followed by focused execution.</p> </AccordeonContent> </AccordeonWrapper> </div> <p style={{ margin: '0px', lineHeight: '10px' }}>&nbsp;</p> <div> <AccordeonTitle open={this.state.visibility[3]} onClick={(e) => this.toggleContent(e, 3)} ref={section => { this.sections[3] = section }} >Project Execution Systems</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[3]}> <p>More and more companies recognize the critical importance of in-house project execution ability. They call on Execution Partners to help them put in place the people, processes, and technology - a “project execution system” - needed to execute projects quickly, efficiently, and successfully – through their own people.</p> <p>It’s important to select the right project management methodology, or set of methodologies, to effectively tackle projects of different types and sizes. Execution Partners can help identify the best methodologies, or blend of methodologies, and adapt them to our clients’ specific situation and needs. Based on the chosen methodologies, we can then help select the technologies and tools best suited to support them. We are technology agnostic and can help set up effective project management processes based on a wide range of tools, from “MS Office project management” to sophisticated total solutions, both cloud-based and on-premise.</p> <p>Most importantly, we can help educate, train, and coach our clients’ in-house project management talent, and help define and implement the right organizational structure to spread, nurture, and develop effective project management practices throughout the organization.</p> <p>Ultimately, an effective Project Execution System enables people to combine project managerial tasks and activities with day-to-day operational activities and responsibilities, helping them stay on top of it all, and succeed in both. The systematized capability to consistently and reliably deliver on complex projects can provide a significant and sustainable competitive advantage.</p> </AccordeonContent> </AccordeonWrapper> <AccordeonTitle open={this.state.visibility[4]} onClick={(e) => this.toggleContent(e, 4)} ref={section => { this.sections[4] = section }} >Manufacturing Execution Systems</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[4]}> <p>Manufacturing Execution Systems (MES) are hardware and software solutions that support efficient and effective Manufacturing Operations Management by “bridging ERP and PLC”. MES forms the foundation for “Smart Manufacturing” or “Industry 4.0” and enables sustainable Operational Excellence by standardizing, integrating, and automating critical manufacturing processes, while empowering people at all levels with access to relevant and accurate information needed to operate and improve on a daily basis.</p> <p>Execution Partners helps its clients understand and navigate the complex and ever-evolving MES landscape. Our unique strength and value-added is in helping leadership teams gain clarity and alignment on the business needs, priorities, future state vision, expected benefits, and return on investment.</p> <p>Except for a partnership with Proceedix* focused on digital work instructions, we are not tied to any specific platform or vendor, which allows us to help our clients find the platform or best-of-breed solution that works best for their specific situation. Our focus is on needs assessment & prioritization, cost/benefit analysis, functional spec creation, solution search & selection, and implementation support. We leave any technical design, development, and integration up to the experts.</p> <p>*Proceedix is a game-changing platform for the digital transformation of enterprise work flows by executing instructions and inspections with mobile and wearable technology, including the brand-new Google Glass Enterprise Edition. Based on our experience in process improvement and system implementation, Proceedix has chosen Execution Partners as its strategic implementation partner for the USA.</p> </AccordeonContent> </AccordeonWrapper> <AccordeonTitle open={this.state.visibility[5]} onClick={(e) => this.toggleContent(e, 5)} ref={section => { this.sections[5] = section }} style={{ paddingBottom: 0 }} >Business Execution Systems</AccordeonTitle> <AccordeonWrapper> <AccordeonContent open={this.state.visibility[5]}> <div style={{ height: '20px' }} /> <p>Many organizations have basic quality management systems in place, such as ISO, or industry-specific quality systems such as TS16949, AS9100TS, or GMP. But the scope and effectiveness of such systems is typically rather limited. Execution Partners helps organizations with the design and implementation of customized Business Execution Systems, based on the Baldrige Performance Excellence framework and EFQM Excellence Model, aligning and integrating the people, processes, and technology needed to run their business successfully and consistently, from enterprise vision to shopfloor operations.</p> <p>Well-designed and properly implemented Business Execution Systems result in focused and motivated people, running efficient and reliable processes, supported by effective technology and tools. Not only do they allow for much higher levels of productivity, they also enable the responsiveness, flexibility, and agility needed to remain competitive and profitable in the marketplace of today - and tomorrow.</p> </AccordeonContent> </AccordeonWrapper> </div> </Slice> <Background large id='method' style={{ height: 'auto' }}> <Overflow> <Visual src={require('./visuals/4. XP Method.png')} style={{ width: '100%', height: 'auto', margin: 0, maxWidth: '1140px', minWidth: '800px' }} /> </Overflow> </Background> <Slice> <H2>Method</H2> <p>Ultimately, it’s all about achieving results that are significant and sustainable. Our method consists of three essential parts that drive each other: a set of efficient and reliable enabler processes supports a focused problem solving approach, which enables the kind of flawless execution that delivers results quickly, efficiently, and sustainably.</p> <p>Our enabler processes represent the typical project management aspects (or “knowledge areas” in PMI terminology) that are crucial for focused execution: identifying and engaging all relevant stakeholders, setting up effective communication, agreeing on a clear scope, objectives, and success metrics, developing a budget and schedule, staying on top of all project tasks and project related information, managing risks and change, and improving overall quality and integration.</p> <p>Our problem solving approach ensures clarity and alignment on definitions and objectives, establishes a clear baseline and targets, defines expected ROI, identifies causes and options, develops and executes a feasible action plan, validates the results, and provides the documentation, training, and support needed to enable continued learning and improvement.</p> <p>Together, our enabler processes and problem solving method significantly improve clarity, alignment, planning, and organization. This allows for focused and well-coordinated execution, with high levels of transparency and accountability, resulting in accelerated progress, faster and deeper learning, and much more sustainable results.</p> </Slice> <Background large id='industries'> <Visual2 src={require('./visuals/5. Playing Field.png')} style={{ width: '100%', height: 'auto', maxWidth: '900px' }} /> </Background> <Slice> <H2>Industries</H2> <p>Our services and methodologies are applicable to very diverse challenges and environments. We’ve worked in industries as varied as automotive, healthcare, and construction. But our main focus is manufacturing. We’ve done projects in many different manufacturing environments, including automotive, plastics extrusion, injection molding, precision metals, steel fabrication, equipment manufacturing, printing, flexible packaging, and cable manufacturing.</p> <p>We’ve helped companies with strategy formulation, strategy execution, business process reengineering, customer experience redesign, software and hardware selection & implementation, strategic sourcing, supplier development, supply chain optimization, operational excellence program development & implementation, business development, startup acceleration, operational assessments, and turnarounds.</p> <p>In short, we are at our best dealing with challenging problems, processes, and projects. And we have a passion for designing -or refining- “execution systems” that enable sustainable results.</p> </Slice> <Background inverse padding> <Quote style={{ marginTop: '20px' }}>Giving the order might be the easiest part. Execution is the real game.</Quote> <Author>Russel L. Honoré</Author> </Background> <Slice id='clients'> <H2>Clients</H2> <Clients> {logos.map((logo, index) => { return <Client key={`logo:${index}`} src={logo.url} style={logo.style} /> })} </Clients> <Small>(representative sample only, and respecting any clients who -as a policy- don’t allow publication of their logo)</Small> </Slice> <Slice inverse> <Quote>We have been extremely pleased with their guidance, support, quality of work, and overall contribution so far. Their very methodical and thorough approach has helped bring the necessary structure and focus to some of our most strategic initiatives. They are smart, hardworking, and very effective at finding solutions and getting things done. Most importantly: they connect well with people and have managed to get different parties aligned on sometimes difficult subjects. I can highly recommend Execution Partners to anyone needing a fresh perspective or focused execution support.</Quote> <Author>Kurt Dallas, Executive Vice President Cable & Connectivity, AFL</Author> </Slice> <Slice id='people'> <H2>People</H2> <Triple column> <div> <Face src={require('./people/stijn.png')} /> <div> <H3>Stijn Van de Velde</H3> <p> Managing Partner<br /> d: +1 (877) 773 9328 x700<br /> e: <a href='mailto:stijn@executionpartners.us'>stijn@executionpartners.us</a><br /> l: <a href='https://www.linkedin.com/in/stijnjvandevelde/' target='blank'>find Stijn on LinkedIn</a></p> </div> </div> <div> <Face src={require('./people/aubrie.jpg')} /> <div> <H3>Aubrie Street</H3> <p> Founding Partner<br /> d: +1 (877) 773 9328 x701<br /> e: <a href='mailto:aubrie@executionpartners.us'>aubrie@executionpartners.us</a><br /> l: <a href='https://www.linkedin.com/in/aubrie-street-b3ab587a/' target='blank'>find Aubrie on LinkedIn</a></p> </div> </div> <div> <Face src={require('./people/joseph.jpg')} /> <div> <H3>Joseph Etris</H3> <p> Partner<br /> d: +1 (877) 773 9328 x702<br /> e: <a href='mailto:joseph@executionpartners.us'>joseph@executionpartners.us</a><br /> l: <a href='https://www.linkedin.com/in/josephetris/' target='blank'>find Joseph on LinkedIn</a></p> </div> </div> </Triple> </Slice> <Background inverse> <Visual src={require('./visuals/6. Exe-cu-tion.png')} style={{ width: '100%', height: 'auto', margin: 0, maxWidth: '600px' }} /> </Background> <Slice id='contact' style={{ minHeight: 'calc(100vh - 146px)' }}> <H2>Contact</H2> <Flex> <div> <div> <p> Execution Partners LLC<br /> 33 Market Point Dr<br /> Greenville, SC 29607<br /> Office: +1 (877) 773 9328<br /> <a href='mailto:info@executionpartners.us'>info@executionpartners.us</a> </p> </div> <p>&nbsp;</p> <MapWithAMarker googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyA0-wRqCiYq9D40V8gwsBx-p0wnSxNtC5A" loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `300px` }} />} mapElement={<div style={{ height: `100%` }} />} /> </div> <div> <Contact /> </div> </Flex> </Slice> <Copy>Copyright Execution Partners LLC 2017&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;All Rights Reserved</Copy> </Wrapper> ) } } const MapWithAMarker = compose( withScriptjs, withGoogleMap )(props => <GoogleMap defaultZoom={12} defaultCenter={{ lat: 34.821889, lng: -82.302172 }} > <Marker position={{ lat: 34.821889, lng: -82.302172 }} /> </GoogleMap> ) class Background extends React.Component { constructor (props) { super(props) console.log(props) } componentDidMount () { } render () { return <BackgroundSlice {...this.props}> {this.props.children} </BackgroundSlice> } } const Wrapper = styled.div` position: relative; ` const Slice = styled.div` position: relative; width: 100%; margin: 0 auto; padding: 30px 20px; @media screen and (min-width: 970px) { padding: 70px 20px; } ${props => props.inverse ? ` background: #333; color: #fff; ` : ` background: #fff; `} @media screen and (min-width: 1200px) { // padding: 70px calc(50% - 570px); padding: 70px calc(50% - 420px); } ` const img = '/bg.jpg' // const img = require('../layouts/greenvillesc2_mini.jpg') const BackgroundSlice = styled.div` width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; background: #000; height: auto; min-height: 150px; overflow: hidden; background: #355e9f url(${img}); background-size: cover; background-attachment: fixed; background-position: bottom center; ${props => props.padding && `padding: 20px;`} @media screen and (min-width: 800px) { padding: 40px 0; } // &:after { // content: ""; // display: block; // position: absolute; // left: 0; // top: 0; // width: 100%; // height: 100%; // background-image: url(${img}); // background-size: cover; // background-attachment: fixed; // background-position: bottom center; // z-index: 0; // opacity: 0.8; // filter: blur(1px) grayscale(0.7); // margin: 0; // -10px -50px -10px -50px; // opacity: 0.5; // } H2 { color: #fff; border-bottom: 1px solid rgba(200, 200, 200, 0.5); padding-bottom: 20px; padding-top: 40px; } ` const H2 = styled.h2` font-family: 'Raleway'; font-weight: 100; font-size: 40px; color: #ccc; @media screen and (min-width: 970px) { font-size: 50px; } @media screen and (min-width: 1440px) { position: absolute; writing-mode: vertical-rl; transform: rotate(180deg); top: 70px; // left: calc(50% - 680px); left: calc(50% - 570px); } ` const H3 = styled.h3` color: #345c9b; font-size: 20px; font-weight: 100; text-transform: uppercase; border-bottom: 1px solid rgba(200, 200, 200, 0.5); padding-bottom: 10px; margin-top: 0; ` const H4 = styled.h4` font-size: 18px; margin: 0; ` const Triple = styled.div` display: flex; justify-content: space-between; ${props => props.column && ` flex-direction: column; `} div { margin-bottom: 20px; } @media screen and (min-width: 960px) { ${props => props.column ? ` flex-direction: column; ` : ` flex-direction: row; `} > div { display: flex; align-items: flex-start; width: 100%; } } ` const Flex = styled.div` display: flex; flex-direction: column; justify-content: space-between; > div { margin-bottom: 20px; } @media screen and (min-width: 970px) { > div { width: 50%; + div { margin-left: 40px; } } } @media screen and (min-width: 960px) { flex-direction: row; } ` const Tag = styled.div` color: #fff; font-size: 24px; padding: 20px 0; margin: 0 auto; text-align: left; font-style: italic; max-width: 740px; line-height: 1.3em; // text-shadow: 0 0 10px rgba(0, 0, 0, 0.7); position: relative; z-index: 10; text-align: center; @media screen and (min-width: 700px) { font-size: 34px; } ` const AccordeonTitle = styled.div` padding: 20px 0; font-size: 16px; font-weight: 700; text-transform: uppercase; cursor: pointer; // &:first-child { // padding-top: 0; // } @media screen and (min-width: 960px) { padding: 20px 0; font-size: 20px; } &:before { content: "+"; display: inline-block; margin-right: 10px; transition: all 0.15s ease-in-out; vertical-align: bottom; font-size: 34px; font-weight: 300; margin-bottom: 20px; vertical-align: top; float: left; ${props => props.open ? ` transform: rotate(45deg); ` : ` transform: rotate(0deg); `} } ${props => props.open && ` color: #355e9f; `} ` const AccordeonWrapper = styled.div` border-bottom: 1px solid rgba(200, 200, 200, 0.5); &:last-child { border-bottom: 0px; } @media screen and (min-width: 960px) { // padding: 0 40px; } ` const AccordeonContent = styled.div` height: auto; overflow: hidden; transition: all 0.3s ease-in-out; ${props => props.open ? ` max-height: 1400px; ` : ` max-height: 0; `} p:last-child { margin-bottom: 20px; } ` const Quote = styled.p` position: relative; padding: 20px 0; margin: 0 auto; font-style: italic; font-size: 18px; line-height: 1.5em; z-index: 10; color: #fff; @media screen and (min-width: 960px) { font-size: 24px; } &:before { content: "“"; display: inline-block; position: absolute; left: -60px; top: 90px; font-size: 400px; color: #444; z-index: -1; font-style: normal; font-family: serif; color: rgba(200, 200, 200, 0.4); } ` const Author = styled.p` color: #eee; text-align: right; margin: 0 auto; ` const Clients = styled.div` display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; align-items: center; justify-content: space-around; ` const Client = styled.img` max-width: 150px; max-height: 80px; filter: grayscale(1); vertical-align: middle; width: 40%; margin: 10px; flex: 0 0 auto; @media screen and (min-width: 960px) { width: auto; margin: 0 20px 30px; } &:hover { filter: none; } ` const Visual1 = styled.img` position: relative; z-index: 5; @media screen and (min-width: 960px) { width: 30% } ` const Visual2 = styled.img` position: relative; z-index: 5; margin: 0; @media screen and (min-width: 960px) { margin: -50px 0; } ` const Visual = styled.img` position: relative; z-index: 5; ` const Face = styled.img` overflow: hidden; width: 180px; margin: 0; margin-right: 20px; filter: grayscale(1); transition: all 0.3s ease-in-out; &:hover { filter: grayscale(0); } ` const Copy = styled.div` position: relative; width: 100%; margin: 0 auto; padding: 30px 20px; text-align: center; background: #333; color: #fff; ` const Overflow = styled.div` width: 100%; height: auto; min-height: 100%; overflow: auto; display: flex; justify-content: flex-start; align-items: center; padding: 20px; @media screen and (min-width: 800px) { justify-content: center; align-items: center; padding: 1px 0; } ` const Small = styled.p` color: #ccc; font-size: 14px; `
src/styles/muiThemeable.js
manchesergit/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import getMuiTheme from './getMuiTheme'; let DEFAULT_THEME; function getDefaultTheme() { if (!DEFAULT_THEME) { DEFAULT_THEME = getMuiTheme(); } return DEFAULT_THEME; } export default function muiThemeable() { return (Component) => { const MuiComponent = (props, context) => { const {muiTheme = getDefaultTheme()} = context; return <Component muiTheme={muiTheme} {...props} />; }; MuiComponent.contextTypes = { muiTheme: PropTypes.object.isRequired, }; return MuiComponent; }; }
js/src/index.js
outeredge/edge-magento-module-menu
import AppContainer from './containers/AppContainer'; import React from 'react'; import ReactDOM from 'react-dom'; const $root = document.getElementById('root'); ReactDOM.render(<AppContainer menu_id={$root.getAttribute('data-menu-id')} token={$root.getAttribute('data-token')} />, $root);
test/test_helper.js
dertnius/React.Beginner
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};
cubetracker-app/src/Cards.js
sandorw/cubetracker
import React from 'react'; import {render} from 'react-dom'; import Button from 'react-bootstrap/lib/Button'; export default class Cards extends React.Component { render() { return ( <Button>Cards</Button> ); } }
src/components/widgets/displayableComponent.js
abbr/ShowPreper
import React from 'react' import classNames from 'classnames' let _ = require('lodash') let DisplayableComponent = class extends React.Component { render() { const { component, container, onSelectedWidgetUpdated, idx, onScaleMouseDown, onRotateMouseDown, onKillMouseDown, setDraggable, editable, componentStyle, ownClassName, combinedTransform, ...rest } = this.props const WidgetFactory = require('./widgetFactory') let Widget = WidgetFactory(component) let widgetStyle = _.merge({ transform: '' }, componentStyle || {}), thisComponentStyle = { transform: '' } if (component.perspective) { thisComponentStyle.transform += ' perspective(' + component.perspective + 'px)' } let translate3D = {} translate3D.x = component.x || 0 translate3D.y = component.y || 0 translate3D.z = component.z || 0 if (!(translate3D.x === 0 && translate3D.y === 0 && translate3D.z === 0)) { thisComponentStyle.transform += ' translate3d(' + translate3D.x + 'px,' + translate3D.y + 'px,' + translate3D.z + 'px)' } component.width && (thisComponentStyle.width = component.width) component.height && (thisComponentStyle.height = component.height) let scaleX = (component.scale && component.scale.x) || 1 let scaleY = (component.scale && component.scale.y) || 1 if (!(scaleX === 1 && scaleY === 1)) { thisComponentStyle.transform += ' scale(' + scaleX + ',' + scaleY + ')' } if (component.rotate) { let rotStr = '' component.rotate.x && (rotStr += ' rotateX(' + component.rotate.x + 'rad)') component.rotate.y && (rotStr += ' rotateY(' + component.rotate.y + 'rad)') component.rotate.z && (rotStr += ' rotateZ(' + component.rotate.z + 'rad)') if (this.props.combinedTransform) { thisComponentStyle.transform += rotStr } else { widgetStyle.transform += rotStr } } if (component.skew) { let rotStr = '' component.skew.y && (rotStr += ' skewY(' + component.skew.y + 'rad)') component.skew.x && (rotStr += ' skewX(' + component.skew.x + 'rad)') if (this.props.combinedTransform) { thisComponentStyle.transform += rotStr } else { widgetStyle.transform += rotStr } } if (widgetStyle.transform === '') { delete widgetStyle.transform } if (thisComponentStyle.transform === '') { delete thisComponentStyle.transform } return ( <div {...rest} className={classNames( 'sp-component', this.props.ownClassName, this.props.className )} style={thisComponentStyle} > <div className={this.props.className} style={{ height: '100%' }}> <Widget {...this.props} className="sp-widget" style={widgetStyle} setDraggable={this.props.setDraggable} /> </div> {this.props.children} </div> ) } } module.exports = DisplayableComponent
app/assets/javascripts/react/views/My/WorkflowEdit.js
Madek/madek-webapp
import React from 'react' import f from 'active-lodash' import cx from 'classnames' import currentLocale from '../../../lib/current-locale' const UI = require('../../ui-components/index.coffee') import SubSection from '../../ui-components/SubSection' import ResourceThumbnail from '../../decorators/ResourceThumbnail.cjsx' import InputMetaDatum from '../../decorators/InputMetaDatum.cjsx' import WorkflowCommonPermissions from '../../decorators/WorkflowCommonPermissions' import RailsForm from '../../lib/forms/rails-form.cjsx' import appRequest from '../../../lib/app-request.coffee' import { Let, IfLet } from '../../lib/lets' import I18nTranslate from '../../../lib/i18n-translate' import labelize from '../../../lib/labelize' let AutoComplete = false // client-side only! const t = I18nTranslate const DEBUG_STATE = false // set to true when developing or debugging forms with state! const HIDE_OVERRIDABLE_TOGGLE = true class WorkflowEdit extends React.Component { constructor(props) { super(props) this.state = { isEditingOwners: false, isSavingOwners: false, ownersUpdateError: null, isEditingPermissions: false, isSavingPermissions: false, permissionsUpdateError: null, isEditingMetadata: false, isSavingMetadata: false, metaDataUpdateError: null, isEditingName: false, isSavingName: false, isProcessing: false, isPreviewing: false, nameUpdateError: null, workflowOwners: props.get.workflow_owners, commonPermissions: props.get.common_settings.permissions, commonMetadata: props.get.common_settings.meta_data } this.actions = [ 'onToggleEditOwners', 'onSaveOwners', 'onToggleEditPermissions', 'onSavePermissions', 'onToggleEditMetadata', 'onSaveMetadata', 'onToggleEditName', 'onSaveName', 'handleFillDataClick', 'handlePreviewClick' ].reduce((o, name) => ({ ...o, [name]: this[name].bind(this) }), {}) } onToggleEditOwners(event) { event.preventDefault() this.setState(cur => ({ isEditingOwners: !cur.isEditingOwners })) } onSaveOwners(owners) { const action = f.get(this, 'props.get.actions.update_owners') if (!action) throw new Error() const finalState = { isEditingOwners: false, isSavingOwners: false } this.setState({ isSavingOwners: true }) const body = { workflow: { owners: f.map(owners, (o) => f.pick(o, ['uuid', 'type'])) } } appRequest({ url: action.url, method: action.method, json: body }, (err, res) => { if (err) { console.error(err) // eslint-disable-line no-console alert('ERROR! ' + JSON.stringify(err)) return this.setState({ ...finalState, ownersUpdateError: err }) } DEBUG_STATE && console.log({ res }) // eslint-disable-line no-console const workflowOwners = f.get(res, 'body.workflow_owners') this.setState({ ...finalState, workflowOwners }) }) } onToggleEditPermissions(event) { event.preventDefault() // NOTE: Date instead of "true" because it's used as React-`key` for the "edit session", // this is done to enforce a freshly mounted component every time, // which is needed because we read props into state! this.setState(cur => ({ isEditingPermissions: cur.isEditingPermissions ? false : Date.now() })) } onSavePermissions(commonPermissions) { const action = f.get(this, 'props.get.actions.update') if (!action) throw new Error() const finalState = { isSavingPermissions: false, isEditingPermissions: false } this.setState({ isSavingPermissions: true }) function prepareData(obj) { const { uuid, type } = obj return { uuid, type } } // tranform form data into what is sent to server: const body = { workflow: { common_permissions: { responsible: f.get(commonPermissions, 'responsible.uuid'), read: f.map(commonPermissions.read, prepareData), write: f.map(commonPermissions.write, prepareData), read_public: commonPermissions.read_public } } } appRequest({ url: action.url, method: action.method, json: body }, (err, res) => { if (err) { console.error(err) // eslint-disable-line no-console alert('ERROR! ' + JSON.stringify(err)) return this.setState({ ...finalState, permissionsUpdateError: err }) } DEBUG_STATE && console.log({ res }) // eslint-disable-line no-console const commonPermissions = f.get(res, 'body.common_settings.permissions') this.setState({ ...finalState, commonPermissions }) }) } onToggleEditMetadata(event) { event.preventDefault() this.setState(cur => ({ isEditingMetadata: cur.isEditingMetadata ? false : Date.now() })) } onSaveMetadata(commonMetadata) { const action = f.get(this, 'props.get.actions.update') if (!action) throw new Error() const finalState = { isSavingMetadata: false, isEditingMetadata: false } this.setState({ isSavingMetadata: true }) function prepareObj(value) { if (f.has(value, 'string')) { return value } else if (f.has(value, 'isNew')) { let v = value if (f.has(value, 'role')) { v.role = value.role.id } return v } else if (f.has(value, 'role')) { return { uuid: value.uuid, role: value.role.id } } else { return { uuid: value.uuid } } } function prepareValue(value) { if (f.isString(value)) { return { string: value } } else if (f.isObject(value)) { return prepareObj(value) } } // tranform form data into what is sent to server: const body = { workflow: { common_meta_data: f.map(commonMetadata, md => ({ meta_key_id: md.meta_key.uuid, value: f.map(md.value, prepareValue), is_common: md.is_common, is_mandatory: md.is_mandatory, is_overridable: md.is_overridable })) } } appRequest({ url: action.url, method: action.method, json: body }, (err, res) => { if (err) { console.error(err) // eslint-disable-line no-console alert('ERROR! ' + JSON.stringify(err)) return this.setState({ finalState, metaDataUpdateError: err }) } DEBUG_STATE && console.log({ res }) // eslint-disable-line no-console const commonMetadata = f.get(res, 'body.common_settings.meta_data') this.setState({ ...finalState, commonMetadata }) }) } onToggleEditName(event) { event.preventDefault() this.setState(cur => ({ isEditingName: cur.isEditingName ? false : Date.now() })) } onSaveName(name) { const action = f.get(this, 'props.get.actions.update') if (!action) throw new Error() const finalState = { isSavingName: false, isEditingName: false } this.setState({ isEditingName: true }) // tranform form data into what is sent to server: const body = { workflow: { name } } appRequest({ url: action.url, method: action.method, json: body }, (err, res) => { if (err) { console.error(err) // eslint-disable-line no-console alert('ERROR! ' + JSON.stringify(err)) return this.setState({ finalState, metaDataUpdateError: err }) } DEBUG_STATE && console.log({ res }) // eslint-disable-line no-console this.setState({ ...finalState, name: f.get(res, 'body.name') }) }) } handleFillDataClick(e) { if (this.state.isProcessing) { e.preventDefault() } this.setState({ isProcessing: true }) } handlePreviewClick() { this.setState({ isPreviewing: true }) } render({ props, state, actions } = this) { const { name, status } = props.get return ( <div> <WorkflowEditor {...{ name, status, authToken: props.authToken, get: props.get }} {...state} {...actions} /> {!!DEBUG_STATE && <ShowJSONData data={{ state, props }} />} </div> ) } } const WorkflowEditor = ({ name, // status, authToken, get, // FIXME: remove this, replace with named props workflowOwners, isEditingOwners, onToggleEditOwners, isSavingOwners, onSaveOwners, commonPermissions, onToggleEditPermissions, isEditingPermissions, isSavingPermissions, onSavePermissions, commonMetadata, onToggleEditMetadata, isEditingMetadata, isSavingMetadata, onSaveMetadata, onToggleEditName, isEditingName, isSavingName, onSaveName, isProcessing, handleFillDataClick, isPreviewing, handlePreviewClick }) => { const supHeadStyle = { textTransform: 'uppercase', fontSize: '85%', letterSpacing: '0.15em' } const headStyle = { lineHeight: '1.34' } const canEdit = get.permissions.can_edit const canEditOwners = get.permissions.can_edit_owners const canPreview = get.permissions.can_preview const isEditing = isEditingName || isEditingOwners || isEditingPermissions || isEditingMetadata return ( <section className="ui-container bright bordered rounded mas pam"> <header> <span style={supHeadStyle}>{t('workflow_feature_title')}</span> {!isEditingName ? ( <h1 className="title-l" style={headStyle}> {name} {' '} {canEdit && <EditButton onClick={onToggleEditName} />} </h1> ) : ( <NameEditor key={isEditingName} name={name} onSave={onSaveName} isSaving={isSavingName} onCancel={onToggleEditName} /> )} </header> <div> <SubSection> <SubSection.Title tag="h2" className="title-m mts"> {t('workflow_associated_collections_title')} </SubSection.Title> <Explainer>{t('workflow_associated_collections_explain')}</Explainer> <div> <div className="ui-resources miniature" style={{ margin: 0 }}> {f.map(get.associated_collections, (collection, i) => ( <ResourceThumbnail get={collection} key={i} /> ))} </div> {canEdit && ( <div className="button-group small mas"> <a className="tertiary-button" href={get.actions.upload.url}> <span> <i className="icon-upload" /> </span>{' '} {t('workflow_associated_collections_upload')} </a> </div> )} </div> </SubSection> <SubSection> <SubSection.Title tag="h2" className="title-m mts"> {t('workflow_owners_title')}{' '} {canEditOwners && !isEditingOwners && <EditButton onClick={onToggleEditOwners} />} </SubSection.Title> {isEditingOwners ? ( <OwnersEditor workflowOwners={workflowOwners} onSave={onSaveOwners} isSaving={isSavingOwners} onCancel={onToggleEditOwners} creator={get.creator} /> ) : ( <UI.TagCloud mod="person" mods="small" list={labelize(workflowOwners)} /> )} </SubSection> <SubSection> <SubSection.Title tag="h2" className="title-m mts"> {t('workflow_common_settings_title')} </SubSection.Title> <Explainer>{t('workflow_common_settings_explain')}</Explainer> <h3 className="title-s mts"> {t('workflow_common_settings_permissions_title')} {' '} {!isEditingPermissions && canEdit && <EditButton onClick={onToggleEditPermissions} />} </h3> <IfLet txt={t('workflow_common_settings_explain_permissions')}> {txt => <Explainer className="mbs">{txt}</Explainer>} </IfLet> {isEditingPermissions ? ( <PermissionsEditor key={isEditingPermissions} commonPermissions={commonPermissions} isSaving={isSavingPermissions} onCancel={onToggleEditPermissions} onSave={onSavePermissions} /> ) : ( <WorkflowCommonPermissions permissions={commonPermissions} /> )} <Explainer>{t('workflow_common_settings_permissions_hint_after')}</Explainer> <h3 className="title-s mts"> {t('workflow_common_settings_metadata_title')} {' '} {!isEditingMetadata && canEdit && <EditButton onClick={onToggleEditMetadata} />} </h3> <Explainer className="mbs"> {t('workflow_common_settings_explain_metadata')} <br /> {t('workflow_common_settings_explain_metadata2')} </Explainer> {isEditingMetadata ? ( <MetadataEditor key={isEditingMetadata} commonMetadata={commonMetadata} isSaving={isSavingMetadata} onCancel={onToggleEditMetadata} onSave={onSaveMetadata} /> ) : ( <Let firstColStyle={{ width: '18rem' }} problems={f.filter(commonMetadata, md => !!md.problem)}> {({ firstColStyle, problems }) => ( <div> <table> <thead> <tr> <th className="prs" style={firstColStyle}> MetaKey </th> <th className="prs">{t('workflow_md_edit_is_mandatory')}</th> <th className="prs">{t('workflow_md_edit_value')}</th> <th className="pls">{t('workflow_md_edit_scope')}</th> </tr> </thead> <tbody> {commonMetadata.map( ({ meta_key, value, is_common, is_mandatory, problem /*, is_overridable*/ }) => { if (problem) return false const decoValues = f.isEmpty(value) ? ( false ) : f.has(value, '0.string') ? ( value[0].string ) : ( <UI.TagCloud mods="small inline" list={labelize(value)} /> ) const hasValueError = is_common && is_mandatory && !isNonEmptyMetaDatumValue(value) return ( <tr key={meta_key.uuid}> <th className="prs" style={firstColStyle}> <span title={meta_key.uuid}>{meta_key.label}</span> </th> <th className="prs text-center"> {is_mandatory ? ( <UI.Icon i="checkmark" title="Pflichtfeld" /> ) : ( <UI.Icon i="close" /> )} </th> <th className={cx('prs', { 'bg-error text-error pls ': hasValueError })}> {is_common ? ( decoValues ? ( <details> <summary className="font-italic"> {t('workflow_md_edit_is_common')} <b>{t('workflow_md_edit_is_common_nonempty')}</b> </summary> {decoValues} </details> ) : ( <div> {hasValueError && ( <UI.Icon i="bang" title={t('workflow_md_edit_value_error_notice')} className="prs" /> )} <em className="font-italic"> {t('workflow_md_edit_is_common')} <b>{t('workflow_md_edit_is_common_empty')}</b> </em> </div> ) ) : ( <em className="font-italic"> {t('workflow_md_edit_is_not_common')} </em> )} </th> <th className="pls"> {f.compact( f .map(meta_key.scope, str => str === 'Entries' ? t('workflow_md_edit_scope_entry') : str === 'Sets' ? t('workflow_md_edit_scope_set') : false ) .join(' & ') )} </th> </tr> ) } )} </tbody> </table> {!f.isEmpty(problems) && ( <div> <b style={{ fontWeight: 'bold' }}>Probleme:</b> {f.map(f.groupBy(problems, 'problem'), (items, problem) => { const problemLabel = problem === 'NOT_FOUND' ? t('workflow_mk_error_not_found') : problem === 'NOT_AUTHORIZED' ? t('workflow_mk_error_not_authorized') : t('workflow_mk_error_unknown') return ( <div key={problem}> <em style={{ fontStyle: 'italic' }}>{problemLabel}</em> <br /> <code>{f.map(items, 'meta_key.uuid').join(', ')}</code> </div> ) })} </div> )} </div> )} </Let> )} </SubSection> </div> {!(isEditingPermissions || isEditingMetadata) && ( <div className="ui-actions phl pbl mtl"> <a className="link weak" href={get.actions.index.url}> {t('workflow_actions_back')} </a> {canPreview && ( <a className={cx('button large', { disabled: isProcessing })} href={get.actions.fill_data.url} onClick={handleFillDataClick}> {isProcessing ? t('workflow_edit_actions_processing') : t('workflow_edit_actions_fill_data')} </a>) } <PreviewButton canPreview={canPreview} isEditing={isEditing} isPreviewing={isPreviewing} previewUrl={get.actions.preview.url} handleClick={handlePreviewClick} /> {/* <button className="tertiary-button large" type="button"> {t('workflow_actions_validate')} </button> */} {canEdit && false && ( <RailsForm action={get.actions.preview.url} method={get.actions.preview.method} name="workflow" style={{ display: 'inline-block' }} authToken={authToken}> {' '} <button className="primary-button large" type="submit" disabled={isEditing}> {t('workflow_actions_finish')} </button> </RailsForm> )} </div> )} </section> ) } module.exports = WorkflowEdit class MetadataEditor extends React.Component { constructor(props) { super(props) this.state = { md: this.props.commonMetadata } AutoComplete = AutoComplete || require('../../lib/autocomplete.cjsx') this.onChangeMdAttr = this.onChangeMdAttr.bind(this) this.onAddMdByMk = this.onAddMdByMk.bind(this) this.onRemoveMd = this.onRemoveMd.bind(this) } onChangeMdAttr(name, attr, val) { // change attribute in metadata list where `name` of input matches MetaKey `id` this.setState(cur => ({ md: cur.md.map(md => (md.meta_key.uuid !== name ? md : { ...md, [attr]: val })) })) } onAddMdByMk(mk) { // add to metadata list for the MetaKey provided by the automcomplete/searcher. const alreadyExists = f.any(this.state.md, md => f.get(mk, 'uuid') === md.meta_key.uuid) if (alreadyExists) return false this.setState(cur => ({ md: cur.md.concat([{ meta_key: mk }]) })) } onRemoveMd(md) { // remove from metadata list the entry matching the mMetaKey `id` this.setState(cur => ({ md: cur.md.filter(curmd => curmd.meta_key.uuid !== md.meta_key.uuid) })) } prepareMdValue(value) { if (f.has(value, '0.string')) { return [value[0].string] } else { return value } } render({ props, state } = this) { const { onSave, onCancel, isSaving } = props const langParam = { lang: currentLocale() } const legendExplains = [ [t('workflow_md_edit_is_common'), t('workflow_md_edit_is_common_explanation')], [t('workflow_md_edit_is_mandatory'), t('workflow_md_edit_is_mandatory_explanation')], [t('workflow_md_edit_remove_btn'), t('workflow_md_edit_remove_explain')] ] return ( <div> {!!isSaving && <SaveBusySignal />} <form className={isSaving ? 'hidden' : null} onSubmit={e => { e.preventDefault() onSave(state.md) }}> <div> <dl className="measure-wide"> <span className="font-italic">{t('workflow_md_edit_legend')}</span> {f.flatten( f.map(legendExplains, ([dt, dd], i) => [ <dt key={'t' + i} className="font-bold"> {dt} </dt>, <dd key={'d' + i} className="font-italic plm"> {dd} </dd> ]) )} </dl> </div> <div className="pvs" style={{ marginLeft: '-10px' }}> {state.md.map((md, i) => ( <Let key={i} name={md.meta_key.uuid} inputId={`emk_${md.meta_key.uuid}`} mkLabel={f.presence(md.meta_key.label)} mkNiceUUID={md.meta_key.uuid.split(':').join(':\u200B')} mdValue={this.prepareMdValue(md.value)} mkdValueError={ md.is_common && md.is_mandatory && !isNonEmptyMetaDatumValue(this.prepareMdValue(md.value)) } problemDesc={ md.problem === 'NOT_FOUND' ? t('workflow_md_edit_mk_error_not_found') : md.problem === 'NOT_AUTHORIZED' ? t('workflow_md_edit_mk_error_not_authorized') : false }> {({ name, inputId, mkLabel, mkNiceUUID, mdValue, mkdValueError, problemDesc }) => ( <div className={cx('ui-form-group pvs columned', { error: md.problem || mkdValueError })}> {problemDesc && <p className="text-error mbs">{problemDesc}</p>} {mkdValueError && ( <p className="text-error mbs">{t('workflow_md_edit_value_error_notice')}</p> )} <div className="form-label"> <label htmlFor={inputId}>{mkLabel || mkNiceUUID}</label> {!!mkLabel && ( <span style={{ fontWeight: 'normal', display: 'block' }}> <small>({mkNiceUUID})</small> </span> )} <div className="mts"> <button type="button" className="button small db mts" onClick={() => this.onRemoveMd(md)}> {t('workflow_md_edit_remove_btn')} </button>{' '} </div> </div> <div className="form-item"> <div className={cx('mbs', !!md.is_common && 'separated pbs')}> <label> <input type="checkbox" name="is_common" checked={!!md.is_common} onChange={e => this.onChangeMdAttr(name, 'is_common', f.get(e, 'target.checked')) } />{' '} {t('workflow_md_edit_is_common')} </label> <br /> {!HIDE_OVERRIDABLE_TOGGLE && ( <div> <label> <input type="checkbox" name="is_overridable" checked={!!md.is_overridable} onChange={e => this.onChangeMdAttr( name, 'is_overridable', f.get(e, 'target.checked') ) } />{' '} {t('workflow_md_edit_is_overridable')} </label> <br /> </div> )} <label> <input type="checkbox" name="is_mandatory" checked={!!md.is_mandatory} onChange={e => this.onChangeMdAttr( name, 'is_mandatory', f.get(e, 'target.checked') ) } />{' '} {t('workflow_md_edit_is_mandatory')} </label> </div> {!!md.is_common && ( <fieldset title="wert"> <legend className="font-italic">Fixen Wert vergeben:</legend> <InputMetaDatum key="item" id={inputId} metaKey={md.meta_key} // NOTE: with plural values this array around value should be removed model={{ values: mdValue }} name={name} onChange={val => this.onChangeMdAttr(name, 'value', f.compact(val))} /> </fieldset> )} </div> </div> )} </Let> ))} </div> <div> {t('workflow_add_md_by_metakey')} <AutoComplete className="block mbs" name="add-meta-key" resourceType="MetaKeys" searchParams={langParam} onSelect={this.onAddMdByMk} existingValueHint={t('workflow_adder_meta_key_already_used')} valueFilter={val => f.any(state.md, md => f.get(val, 'uuid') === md.meta_key.uuid)} /> </div> <div className="pts pbs"> <button type="submit" className="button primary-button"> {t('workflow_edit_actions_save_data')} </button>{' '} <button type="button" className="button" onClick={onCancel}> {t('workflow_edit_actions_cancel')} </button> </div> </form> {!!DEBUG_STATE && <ShowJSONData data={{ state, props }} />} </div> ) } } class PermissionsEditor extends React.Component { constructor(props) { super(props) this.state = { ...this.props.commonPermissions } AutoComplete = AutoComplete || require('../../lib/autocomplete.cjsx') this.onSetResponsible = this.onSetResponsible.bind(this) this.onRemoveResponsible = this.onRemoveResponsible.bind(this) this.onTogglePublicRead = this.onTogglePublicRead.bind(this) this.onAddPermissionEntity = this.onAddPermissionEntity.bind(this) this.onRemovePermissionEntity = this.onRemovePermissionEntity.bind(this) } onSetResponsible(obj) { this.setState({ responsible: obj }) } onRemoveResponsible() { this.setState({ responsible: null }) } onTogglePublicRead() { this.setState(cur => ({ read_public: !cur.read_public })) } onAddPermissionEntity(listKey, obj) { this.setState(cur => ({ [listKey]: cur[listKey].concat(obj) })) } onRemovePermissionEntity(listKey, obj) { this.setState(cur => ({ [listKey]: cur[listKey].filter(item => item.uuid !== obj.uuid) })) } render({ props, state } = this) { const { onSave, onCancel, isSaving } = props return ( <div> {!!isSaving && <SaveBusySignal />} <form className={isSaving ? 'hidden' : null} onSubmit={e => { e.preventDefault() onSave(this.state) }}> <ul> <li> <span className="title-s"> {t('workflow_common_settings_permissions_responsible')}:{' '} </span> <UI.TagCloud mod="person" mods="small inline" list={labelize([state.responsible], { onDelete: this.onRemoveResponsible })} /> <div className="row"> <div className="col1of3"> {t('workflow_common_settings_permissions_select_user')}:{' '} <AutocompleteAdder type={["Delegations", "Users"]} onSelect={this.onSetResponsible} valueFilter={val => f.get(state.responsible, 'uuid') === f.get(val, 'uuid')} /> </div> </div> </li> <li> <span className="title-s"> {t('workflow_common_settings_permissions_write')} {': '} </span> <UI.TagCloud mod="person" mods="small inline" list={labelize(state.write, { onDelete: f.curry(this.onRemovePermissionEntity)('write') })} /> <MultiAdder onAdd={f.curry(this.onAddPermissionEntity)('write')} permissionsScope="write" /> </li> <li> <span className="title-s"> {t('workflow_common_settings_permissions_read')} {': '} </span> <UI.TagCloud mod="person" mods="small inline" list={labelize(state.read, { onDelete: f.curry(this.onRemovePermissionEntity)('read') })} /> <MultiAdder onAdd={f.curry(this.onAddPermissionEntity)('read')} permissionsScope="read" /> </li> <li> <span className="title-s"> {t('workflow_common_settings_permissions_read_public')} {': '} </span> <input type="checkbox" checked={state.read_public} onChange={this.onTogglePublicRead} /> </li> </ul> <div className="pts pbs"> <button type="submit" className="button primary-button"> {t('workflow_edit_actions_save_data')} </button>{' '} <button type="button" className="button" onClick={onCancel}> {t('workflow_edit_actions_cancel')} </button> </div> </form> {!!DEBUG_STATE && <ShowJSONData data={{ state, props }} />} </div> ) } } class NameEditor extends React.Component { constructor(props) { super(props) this.state = { name: this.props.name } this.onSetName = this.onSetName.bind(this) } onSetName({ target }) { this.setState({ name: target.value }) } render({ props, state } = this) { const { onSave, onCancel, isSaving } = props // like .title-l class: const inputStyle = { fontSize: '17px', fontWeight: '700' } return ( <div className="pts"> {!!isSaving && <SaveBusySignal />} <form className={isSaving ? 'hidden' : null} onSubmit={e => { e.preventDefault() onSave(this.state.name) }}> <input type="text" className="block" value={state.name} onChange={this.onSetName} style={inputStyle} /> <div className="pts pbs"> <button type="submit" className="button primary-button"> {t('workflow_edit_actions_save_data')} </button>{' '} <button type="button" className="button" onClick={onCancel}> {t('workflow_edit_actions_cancel')} </button> </div> </form> {!!DEBUG_STATE && <ShowJSONData data={{ state, props }} />} </div> ) } } class OwnersEditor extends React.Component { constructor(props) { super(props) this.state = { owners: this.props.workflowOwners } AutoComplete = AutoComplete || require('../../lib/autocomplete.cjsx') this.onAddOwner = this.onAddOwner.bind(this) this.onRemoveOwner = this.onRemoveOwner.bind(this) } onAddOwner(owner) { this.setState(cur => ({ owners: f.uniq(cur.owners.concat(owner), 'uuid') })) } onRemoveOwner(owner) { this.setState(cur => ({ owners: cur.owners.filter(item => item.uuid !== owner.uuid) })) } render({ props, state } = this) { return ( <div> {!!props.isSaving && <SaveBusySignal />} <form onSubmit={e => { e.preventDefault() props.onSave(state.owners) }}> <UI.TagCloud mod="person" mods="small" list={labelize(this.state.owners, { onDelete: this.onRemoveOwner, creatorId: props.creator.uuid })} /> <div className="row"> <div className="col1of3"> {t('workflow_common_settings_permissions_select_owner')}:{' '} <AutocompleteAdder type={['Delegations', 'Users']} onSelect={this.onAddOwner} valueFilter={({ uuid }) => f.includes(f.map(this.state.owners, 'uuid'), uuid)} /> </div> </div> <div className="pts pbs"> <button type="submit" className="button primary-button"> SAVE </button>{' '} <button type="button" className="button" onClick={props.onCancel}> CANCEL </button> </div> </form> </div> ) } } const Explainer = ({ className, children }) => ( <p className={cx('paragraph-s mts measure-wide', className)} style={{ fontStyle: 'italic' }}> {children} </p> ) const EditButton = ({ onClick, icon = 'icon-pen', ...props }) => { return ( <button {...props} onClick={onClick} style={{ background: 'transparent', WebkitAppearance: 'none' }}> <small className="link">{!f.isEmpty(icon) && <i className={icon} />}</small> </button> ) } const PreviewButton = ({ handleClick, canPreview, isEditing, isPreviewing, previewUrl }) => { const cssClasses = cx('primary-button large', { disabled: isEditing || isPreviewing }) const disabledButton = ( <div className={cssClasses}> {isPreviewing ? t('workflow_actions_validating') : t('workflow_actions_validate')} </div> ) const regularButton = ( <a className={cssClasses} href={previewUrl} onClick={handleClick}> {t('workflow_actions_validate')} </a> ) return canPreview && (isEditing || isPreviewing ? disabledButton : regularButton) } const AutocompleteAdder = ({ type, currentValues, ...props }) => { const valueFilter = props.valueFilter || (({ uuid }) => f.includes(f.map(currentValues, 'subject.uuid'), uuid)) return ( <span style={{ position: 'relative' }}> <AutoComplete className="block" name="autocompleter" {...props} resourceType={type} valueFilter={valueFilter} /> </span> ) } const MultiAdder = ({ currentUsers, currentGroups, currentApiClients, onAdd, permissionsScope }) => ( <div className="row pts pbm"> <div className="col1of3"> <div className=""> {t('workflow_common_settings_permissions_add_user')}:{' '} <AutocompleteAdder type="Users" onSelect={onAdd} currentValues={currentUsers} /> </div> </div> <div className="col1of3"> <div className="pls"> {t('workflow_common_settings_permissions_add_group')}:{' '} <AutocompleteAdder type="Groups" searchParams={{ scope: 'permissions' }} onSelect={onAdd} currentValues={currentGroups} /> </div> </div> {permissionsScope === 'read' && ( <div className="col1of3"> <div className="pls"> {t('workflow_common_settings_permissions_add_api_client')}:{' '} <AutocompleteAdder type="ApiClients" onSelect={onAdd} currentValues={currentApiClients} /> </div> </div> )} </div> ) const SaveBusySignal = () => ( <div className="pal" style={{ textAlign: 'center' }}> {'Saving…'} </div> ) const ShowJSONData = ({ data }) => ( <div> <hr /> <pre className="mas pam code">{JSON.stringify(data, 0, 2)}</pre> </div> ) const isNonEmptyMetaDatumValue = val => { const isNonEmpty = i => !f.isEmpty(f.isString ? f.trim(i) : i) if (!val) return false if (f.isArray(val)) return f.any(f.compact(val), isNonEmpty) else return isNonEmpty(val) }
src/components/WalletBackup.js
jhkmjnhamster/vcash-electron
import React from 'react' import { translate } from 'react-i18next' import { action, computed, observable } from 'mobx' import { inject, observer } from 'mobx-react' import { Button, Input, message } from 'antd' import { remote } from 'electron' import { join, sep } from 'path' import { dataPath } from '../utilities/common' @translate(['wallet'], { wait: true }) @inject('rpc') @observer class WalletBackup extends React.Component { @observable error = false @observable path constructor (props) { super(props) this.t = props.t this.rpc = props.rpc this.path = this.rpc.connection.status.tunnel === true ? '' : join(dataPath(), 'backups', sep) } /** * Get error status. * @function errorStatus * @return {string|false} Current error or false if none. */ @computed get errorStatus () { if (this.error !== false) return this.error return false } /** * Set RPC error. * @function setError * @param {string} error - RPC error. */ @action setError = (error = false) => { this.error = error } /** * Set backup path. * @function setPath */ @action setPath = () => { /** Open directory browser. */ const selected = remote.dialog.showOpenDialog({ properties: ['openDirectory'] }) /** Set selected path. */ if (typeof selected !== 'undefined') { this.path = join(selected[0], sep) } } /** * Backup the wallet. * @function backup */ backup = () => { this.rpc.execute( [{ method: 'backupwallet', params: [this.path] }], response => { /** Display a success message. */ if (response[0].hasOwnProperty('result') === true) { message.success(this.t('wallet:backedUp'), 6) } /** Set error. */ if (response[0].hasOwnProperty('error') === true) { switch (response[0].error.code) { /** error_code_wallet_error */ case -4: return this.setError('backupFailed') } } } ) } render () { return ( <div> <div className='flex'> <i className='material-icons md-16'>save</i> <p>{this.t('wallet:backupLong')}</p> </div> <div className='flex-sb' style={{ margin: '10px 0 0 0' }}> <p style={{ width: '120px' }}>{this.t('wallet:saveInto')}</p> <Input disabled style={{ flex: 1 }} value={ this.rpc.connection.status.tunnel === true ? this.t('wallet:remoteDataFolder') : this.path } /> </div> <div className='flex-sb' style={{ alignItems: 'flex-start', margin: '5px 0 0 0' }} > <p className='red' style={{ margin: '0 0 0 120px' }}> {this.errorStatus === 'backupFailed' && this.t('wallet:backupFailed')} </p> <div className='flex' style={{ justifyContent: 'flex-end' }}> <Button disabled={this.rpc.connection.status.tunnel === true} onClick={this.setPath} style={{ margin: '0 5px 0 0' }} > {this.t('wallet:browse')} </Button> <Button onClick={this.backup}>{this.t('wallet:backup')}</Button> </div> </div> </div> ) } } export default WalletBackup
src/interface/others/DeathRecap.js
FaideWW/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Slider from 'rc-slider'; import 'rc-slider/assets/index.css'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Icon from 'common/Icon'; import { formatDuration, formatNumber, formatPercentage } from 'common/format'; import WarcraftLogsLogo from 'interface/images/WarcraftLogs-logo.png'; const SHOW_SECONDS_BEFORE_DEATH = 10; const AMOUNT_THRESHOLD = 0; class DeathRecap extends React.PureComponent { static propTypes = { events: PropTypes.array.isRequired, enemies: PropTypes.object.isRequired, combatants: PropTypes.object.isRequired, report: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { detailedView: 0, amountThreshold: AMOUNT_THRESHOLD, }; this.handleClick = this.handleClick.bind(this); } handleClick(event) { const clicked = event === this.state.detailedView ? -1 : event; this.setState({ detailedView: clicked }); } render() { let lastHitPoints = 0; let lastMaxHitPoints = 0; function sortByTimelineIndex(a, b) { return a.timelineSortIndex - b.timelineSortIndex; } const sliderProps = { min: 0, max: 1, step: 0.05, marks: { 0: '0%', 0.1: '10%', 0.2: '20%', 0.3: '30%', 0.4: '40%', 0.5: '50%', 0.6: '60%', 0.7: '70%', 0.8: '80%', 0.9: '90%', 1: '100%', }, style: { margin: '0px 2em 4em 2em', width: 'calc(100% - 4em)', }, }; const events = this.props.events; return ( <div> <div style={{ overflow: 'auto' }}> <div style={{ float: 'left', width: 'calc(100% - 20em)' }}> <div style={{ margin: '2em 0 0 2em' }}> Filter events based on min amount (percentage of players health): </div> <Slider {...sliderProps} defaultValue={this.state.amountThreshold} onChange={(value) => { this.setState({ amountThreshold: value, }); }} /> </div> <div style={{ width: '18em', float: 'left', marginTop: '2em' }}> <a href={`https://www.warcraftlogs.com/reports/${this.props.report.report.code}#fight=${this.props.report.fight.id}&type=deaths&source=${this.props.report.player.id}`} target="_blank" rel="noopener noreferrer" className="btn" style={{ fontSize: 24 }} data-tip="Open the deaths on Warcraft Logs" > <img src={WarcraftLogsLogo} alt="Warcraft Logs logo" style={{ height: '1.4em', marginTop: '-0.15em' }} /> Warcraft Logs </a> </div> </div> {events.map((death, i) => ( <div className="item-divider-top"> <h2 onClick={() => this.handleClick(i)} style={{ padding: '10px 20px', cursor: 'pointer' }}>Death #{i + 1}</h2> <table style={{ display: this.state.detailedView === i ? 'block' : 'none' }} className="data-table"> <thead> <tr> <th>Time</th> <th>Ability</th> <th>HP</th> <th>Amount</th> <th>Defensive Buffs/Debuffs</th> <th>Personals available</th> </tr> </thead> <tbody> {death.events .filter(e => e.timestamp <= death.deathtime && e.timestamp >= death.deathtime - (SHOW_SECONDS_BEFORE_DEATH * 1000)) .filter(e => ((e.amount + (e.absorbed || 0)) / e.maxHitPoints > this.state.amountThreshold) || e.type === 'instakill') .map(event => { if (event.hitPoints && event.maxHitPoints) { lastHitPoints = event.hitPoints; lastMaxHitPoints = event.maxHitPoints; } const hitPercent = event.amount / lastMaxHitPoints; let percent = 0; let output = null; //name = either NPC-Name > sourceID-Name > Ability-Name as fallback let sourceName = event.source && event.source.type === 'NPC' ? event.source.name : null; if (!sourceName && event.type === 'heal') { sourceName = this.props.combatants[event.sourceID] ? this.props.combatants[event.sourceID]._combatantInfo.name : null; } if (!sourceName && event.type === 'damage') { sourceName = this.props.enemies[event.sourceID] ? this.props.enemies[event.sourceID]._baseInfo.name : null; } if (!sourceName && event.type !== 'instakill') { sourceName = event.ability.name; } if (event.type === 'heal') { percent = (lastHitPoints - event.amount) / lastMaxHitPoints; output = ( <dfn data-tip={` ${event.sourceID === event.targetID ? `You healed yourself for ${formatNumber(event.amount)}` : `${sourceName} healed you for ${formatNumber(event.amount)}` } ${event.absorbed > 0 ? `, ${formatNumber(event.absorbed)} of that healing was absorbed` : ''} ${event.overheal > 0 ? ` and overhealed for ${formatNumber(event.overheal)}<br/>` : ''} `} style={(event.amount === 0 && event.absorbed > 0) ? {color: 'orange'} : {color: 'green'}}> +{formatNumber(event.amount)} {event.absorbed > 0 ? `(A: ${formatNumber(event.absorbed)} )` : ''} {event.overheal > 0 ? `(O: ${formatNumber(event.overheal)} )` : ''} </dfn> ); } else if (event.type === 'damage') { percent = lastHitPoints / lastMaxHitPoints; output = ( <dfn data-tip={` ${event.sourceID === event.targetID ? `You damaged yourself for ${formatNumber(event.amount)}<br/>` : `${sourceName} damaged you for a total of ${formatNumber(event.amount + (event.absorbed || 0))}<br/>` } ${event.absorbed > 0 ? `${formatNumber(event.absorbed)} of this damage was absorbed and you took ${formatNumber(event.amount)} damage<br/>` : ''} `} style={{ color: 'red' }}> -{formatNumber(event.amount)} {event.absorbed > 0 ? `(A: ${formatNumber(event.absorbed)} )` : ''} </dfn> ); } else if (event.type === 'instakill') { percent = 0; output = '1-Shot'; } if (event.overkill || event.hitPoints === 0) { percent = 0; } return ( <tr> <td style={{ width: '5%' }}> {formatDuration(event.time / 1000, 2)} </td> <td style={{ width: '20%' }}> <SpellLink id={event.ability.guid} icon={false}> <Icon icon={event.ability.abilityIcon} /> {event.ability.name} </SpellLink> </td> <td style={{ width: '20%' }}> <div className="flex performance-bar-container"> {percent !== 0 && ( <div className="flex-sub performance-bar" style={{ color: 'white', width: formatPercentage(percent) + '%' }} /> )} <div className="flex-sub performance-bar" style={{ backgroundColor: event.type === 'heal' ? 'green' : 'red', width: formatPercentage(hitPercent) + '%', opacity: event.type === 'heal' ? .8 : .4, }} /> </div> </td> <td style={{ width: '15%' }}> {output} </td> <td style={{ width: '20%' }}> {event.buffsUp && event.buffsUp.sort(sortByTimelineIndex).map(e => <SpellIcon style={{ border: '1px solid rgba(0, 0, 0, 0)' }} id={e.id} /> )}<br /> {event.debuffsUp && event.debuffsUp.sort(sortByTimelineIndex).map(e => <SpellIcon style={{ border: '1px solid red' }} id={e.id} /> )} </td> <td style={{ width: '20%' }}> {event.defensiveCooldowns.sort(sortByTimelineIndex).map(e => <SpellIcon style={{ opacity: e.cooldownReady ? 1 : .2 }} id={e.id} /> )} </td> </tr> ); })} <tr> <td /> <td colSpan="6"> You died </td> </tr> </tbody> </table> </div> ))} </div> ); } } export default DeathRecap;
scripts/PianoRoll.js
stevenpetryk/midi-scorer
import React from 'react' import Immutable from 'immutable' import moment from 'moment' import NotePress from './NotePress' const SCALE_VALUE = 25.0 export default React.createClass({ propTypes: { startTime: React.PropTypes.any, notePresses: React.PropTypes.arrayOf(React.PropTypes.arrayOf(React.PropTypes.instanceOf(NotePress))).isRequired }, getNotePresses (keyStack) { return keyStack.map((notePress, i) => { var endedAt = notePress.endedAt.isValid() ? notePress.endedAt : moment().add(20, 'ms') var duration = endedAt.diff(notePress.beganAt) var timeSinceStart = moment().diff(notePress.beganAt) var width = Math.floor(duration / SCALE_VALUE) var right = Math.ceil(timeSinceStart / SCALE_VALUE - width) return ( <div style={{right, width}} className='piano-roll-key-event' key={i}>&nbsp;</div> ) }) }, getPitches () { return Immutable.Range(76, 47).toJS().map((note) => { var keyStack = this.props.notePresses[note] return ( <div key={note} className='piano-roll-note'> {this.getNotePresses(keyStack)} </div> ) }) }, /** * Renders the component */ render () { return ( <div className='piano-roll'> {this.getPitches()} </div> ) } })
src/components/DeveloperMenu.ios.js
jacktuck/registr
import React from 'react'; import * as snapshot from '../utils/snapshot'; import { TouchableOpacity, ActionSheetIOS, StyleSheet } from 'react-native'; /** * Simple developer menu, which allows e.g. to clear the app state. * It can be accessed through a tiny button in the bottom right corner of the screen. * ONLY FOR DEVELOPMENT MODE! */ const DeveloperMenu = React.createClass({ displayName: 'DeveloperMenu', showDeveloperMenu() { const options = { clearState: 0, showLogin: 1, cancel: 2 }; const callback = async index => { if (index === options.clearState) { await snapshot.clearSnapshot(); console.warn('(╯°□°)╯︵ ┻━┻ \nState cleared, Cmd+R to reload the application now'); } }; ActionSheetIOS.showActionSheetWithOptions({ options: [ 'Clear state', 'Cancel' ], cancelButtonIndex: options.cancel }, callback); }, render() { if (!__DEV__) { return null; } return ( <TouchableOpacity style={styles.circle} onPress={this.showDeveloperMenu} /> ); } }); const styles = StyleSheet.create({ circle: { position: 'absolute', bottom: 5, right: 5, width: 10, height: 10, borderRadius: 5, backgroundColor: '#000' } }); export default DeveloperMenu;
src/static/utils/requireAuthentication.js
SeaItRise/SeaItRise-webportal
import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; export default function requireAuthentication(Component) { class AuthenticatedComponent extends React.Component { static propTypes = { isAuthenticated: React.PropTypes.bool.isRequired, location: React.PropTypes.shape({ pathname: React.PropTypes.string.isRequired }).isRequired, dispatch: React.PropTypes.func.isRequired }; componentWillMount() { this.checkAuth(); } componentWillReceiveProps(nextProps) { this.checkAuth(); } checkAuth() { if (!this.props.isAuthenticated) { const redirectAfterLogin = this.props.location.pathname; this.props.dispatch(push(`/login?next=${redirectAfterLogin}`)); } } render() { return ( <div> {this.props.isAuthenticated === true ? <Component {...this.props} /> : null } </div> ); } } const mapStateToProps = (state) => { return { isAuthenticated: state.auth.isAuthenticated, token: state.auth.token }; }; return connect(mapStateToProps)(AuthenticatedComponent); }
src/svg-icons/image/color-lens.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageColorLens = (props) => ( <SvgIcon {...props}> <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); ImageColorLens = pure(ImageColorLens); ImageColorLens.displayName = 'ImageColorLens'; ImageColorLens.muiName = 'SvgIcon'; export default ImageColorLens;
examples/src/components/CustomOption.js
naturalatlas/react-select
import React from 'react'; import Gravatar from 'react-gravatar'; var Option = React.createClass({ propTypes: { addLabelText: React.PropTypes.string, className: React.PropTypes.string, mouseDown: React.PropTypes.func, mouseEnter: React.PropTypes.func, mouseLeave: React.PropTypes.func, option: React.PropTypes.object.isRequired, renderFunc: React.PropTypes.func }, render () { var obj = this.props.option; var size = 15; var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown}> <Gravatar email={obj.email} size={size} style={gravatarStyle} /> {obj.value} </div> ); } }); module.exports = Option;
app/javascript/mastodon/components/column_back_button_slim.js
WitchesTown/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import ColumnBackButton from './column_back_button'; export default class ColumnBackButtonSlim extends ColumnBackButton { render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
app/javascript/mastodon/features/lists/components/new_list_form.js
ashfurrow/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { changeListEditorTitle, submitListEditor } from '../../../actions/lists'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' }, title: { id: 'lists.new.create', defaultMessage: 'Add list' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'title']), disabled: state.getIn(['listEditor', 'isSubmitting']), }); const mapDispatchToProps = dispatch => ({ onChange: value => dispatch(changeListEditorTitle(value)), onSubmit: () => dispatch(submitListEditor(true)), }); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class NewListForm extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, disabled: PropTypes.bool, intl: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleSubmit = e => { e.preventDefault(); this.props.onSubmit(); } handleClick = () => { this.props.onSubmit(); } render () { const { value, disabled, intl } = this.props; const label = intl.formatMessage(messages.label); const title = intl.formatMessage(messages.title); return ( <form className='column-inline-form' onSubmit={this.handleSubmit}> <label> <span style={{ display: 'none' }}>{label}</span> <input className='setting-text' value={value} disabled={disabled} onChange={this.handleChange} placeholder={label} /> </label> <IconButton disabled={disabled || !value} icon='plus' title={title} onClick={this.handleClick} /> </form> ); } }
app/components/layout/newProject/TrackSelector.js
communicode-source/communicode
import React from 'react'; import PropTypes from 'prop-types'; import styles from './../../../assets/css/pages/createProject.scss'; class TrackSelector extends React.Component { constructor(props) { super(props); this.props = props; } handleTrackSelect(e) { if(e.target.value === 'Select...') { return this.props.selectProjectTrack(''); } return this.props.selectProjectTrack(e.target.value); } render() { return ( <div className={styles.question}> <h4>Or select a track...</h4> <select value={(this.props.track === '') ? 'Select...' : this.props.track} onChange={this.handleTrackSelect.bind(this)} name="tracks"> <option value={null}>Select...</option> <option value="Mobile">Mobile</option> <option value="Website">Website</option> <option value="API">API Help</option> <option value="Big Data">Big Data</option> <option value="Sleep">Sleep</option> </select> </div> ); } } TrackSelector.propTypes = { track: PropTypes.string, selectProjectTrack: PropTypes.func }; export default TrackSelector;
examples/cra-ts-essentials/.storybook/preview.js
storybooks/storybook
import React from 'react'; export const decorators = [ (StoryFn, { globals: { locale = 'en' } }) => ( <> <div>{locale}</div> <StoryFn /> </> ), ]; export const globalTypes = { locale: { name: 'Locale', description: 'Internationalization locale', defaultValue: 'en', toolbar: { icon: 'globe', items: [ { value: 'en', right: '🇺🇸', title: 'English' }, { value: 'es', right: '🇪🇸', title: 'Español' }, { value: 'zh', right: '🇨🇳', title: '中文' }, { value: 'kr', right: '🇰🇷', title: '한국어' }, ], }, }, };
src/components/CheckboxLabel.js
devdlx/foxxiee
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable */ import React from 'react'; export default function CheckboxLabel(props) { const {id, children} = props; const controlId = props['for']; return ( <label className="mdc-checkbox-label" id={id} htmlFor={controlId}>{children}</label> ); }
src/client/components/me.js
vacuumlabs/todolist
import Logout from './logout'; import React from 'react'; import auth from './common/auth'; class Me extends React.Component { render() { return ( <div> <p> This is your secret page. </p> <Logout /> </div> ); } } export default auth(Me);
app/javascript/flavours/glitch/features/directory/index.js
im-in-space/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from 'flavours/glitch/components/column'; import ColumnHeader from 'flavours/glitch/components/column_header'; import { addColumn, removeColumn, moveColumn, changeColumnParams } from 'flavours/glitch/actions/columns'; import { fetchDirectory, expandDirectory } from 'flavours/glitch/actions/directory'; import { List as ImmutableList } from 'immutable'; import AccountCard from './components/account_card'; import RadioButton from 'flavours/glitch/components/radio_button'; import LoadMore from 'flavours/glitch/components/load_more'; import ScrollContainer from 'flavours/glitch/containers/scroll_container'; import LoadingIndicator from 'flavours/glitch/components/loading_indicator'; const messages = defineMessages({ title: { id: 'column.directory', defaultMessage: 'Browse profiles' }, recentlyActive: { id: 'directory.recently_active', defaultMessage: 'Recently active' }, newArrivals: { id: 'directory.new_arrivals', defaultMessage: 'New arrivals' }, local: { id: 'directory.local', defaultMessage: 'From {domain} only' }, federated: { id: 'directory.federated', defaultMessage: 'From known fediverse' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'directory', 'items'], ImmutableList()), isLoading: state.getIn(['user_lists', 'directory', 'isLoading'], true), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class Directory extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list.isRequired, dispatch: PropTypes.func.isRequired, columnId: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, domain: PropTypes.string.isRequired, params: PropTypes.shape({ order: PropTypes.string, local: PropTypes.bool, }), }; state = { order: null, local: null, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('DIRECTORY', this.getParams(this.props, this.state))); } } getParams = (props, state) => ({ order: state.order === null ? (props.params.order || 'active') : state.order, local: state.local === null ? (props.params.local || false) : state.local, }); handleMove = dir => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch } = this.props; dispatch(fetchDirectory(this.getParams(this.props, this.state))); } componentDidUpdate (prevProps, prevState) { const { dispatch } = this.props; const paramsOld = this.getParams(prevProps, prevState); const paramsNew = this.getParams(this.props, this.state); if (paramsOld.order !== paramsNew.order || paramsOld.local !== paramsNew.local) { dispatch(fetchDirectory(paramsNew)); } } setRef = c => { this.column = c; } handleChangeOrder = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['order'], e.target.value)); } else { this.setState({ order: e.target.value }); } } handleChangeLocal = e => { const { dispatch, columnId } = this.props; if (columnId) { dispatch(changeColumnParams(columnId, ['local'], e.target.value === '1')); } else { this.setState({ local: e.target.value === '1' }); } } handleLoadMore = () => { const { dispatch } = this.props; dispatch(expandDirectory(this.getParams(this.props, this.state))); } render () { const { isLoading, accountIds, intl, columnId, multiColumn, domain } = this.props; const { order, local } = this.getParams(this.props, this.state); const pinned = !!columnId; const scrollableArea = ( <div className='scrollable'> <div className='filter-form'> <div className='filter-form__column' role='group'> <RadioButton name='order' value='active' label={intl.formatMessage(messages.recentlyActive)} checked={order === 'active'} onChange={this.handleChangeOrder} /> <RadioButton name='order' value='new' label={intl.formatMessage(messages.newArrivals)} checked={order === 'new'} onChange={this.handleChangeOrder} /> </div> <div className='filter-form__column' role='group'> <RadioButton name='local' value='1' label={intl.formatMessage(messages.local, { domain })} checked={local} onChange={this.handleChangeLocal} /> <RadioButton name='local' value='0' label={intl.formatMessage(messages.federated)} checked={!local} onChange={this.handleChangeLocal} /> </div> </div> <div className='directory__list'> {isLoading ? <LoadingIndicator /> : accountIds.map(accountId => ( <AccountCard id={accountId} key={accountId} /> ))} </div> <LoadMore onClick={this.handleLoadMore} visible={!isLoading} /> </div> ); return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='address-book-o' title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} /> {multiColumn && !pinned ? <ScrollContainer scrollKey='directory'>{scrollableArea}</ScrollContainer> : scrollableArea} </Column> ); } }
blueocean-material-icons/src/js/components/svg-icons/action/shop-two.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionShopTwo = (props) => ( <SvgIcon {...props}> <path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9zm15-4V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm0 12V8l5.5 3-5.5 4z"/> </SvgIcon> ); ActionShopTwo.displayName = 'ActionShopTwo'; ActionShopTwo.muiName = 'SvgIcon'; export default ActionShopTwo;
src/svg-icons/maps/directions-railway.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsRailway = (props) => ( <SvgIcon {...props}> <path d="M4 15.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5zm8 1.5c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6-7H6V5h12v5z"/> </SvgIcon> ); MapsDirectionsRailway = pure(MapsDirectionsRailway); MapsDirectionsRailway.displayName = 'MapsDirectionsRailway'; MapsDirectionsRailway.muiName = 'SvgIcon'; export default MapsDirectionsRailway;
src/components/TimeFilter.js
springload/reusable-d3-charts
import React from 'react'; import Select from 'react-simpler-select'; import Button from '../components/Button'; /** * Time filtering UI, for the user to "zoom in" on a smaller length of time. */ const TimeFilter = ({ availableYears, filterTo, filterFrom, handleChangeFrom, handleChangeTo, resetTimeFilter }) => { const hasFilter = filterFrom || filterTo; const fromValue = filterFrom || availableYears[0]; const toValue = filterTo || availableYears[availableYears.length - 1]; return ( <form className="form-inline text--"> <label className="select"> <Select name="from" value={fromValue} options={availableYears} onChange={handleChangeFrom} /> </label> <span> - </span> <label className="select"> <Select name="to" value={toValue} options={availableYears.slice().reverse()} onChange={handleChangeTo} /> </label> {hasFilter ? ( <Button className="btn--link" onClick={resetTimeFilter} > All </Button> ) : null} </form> ); }; TimeFilter.propTypes = { availableYears: React.PropTypes.array.isRequired, filterFrom: React.PropTypes.number, filterTo: React.PropTypes.number, handleChangeFrom: React.PropTypes.func.isRequired, handleChangeTo: React.PropTypes.func.isRequired, resetTimeFilter: React.PropTypes.func.isRequired, }; export default TimeFilter;
information/blendle-frontend-react-source/app/containers/ApplicationContainer.js
BramscoChill/BlendleParser
import i18n from 'instances/i18n'; import Country from 'instances/country'; import ApplicationState from 'instances/application_state'; import Analytics from 'instances/analytics'; import logPerformance from 'helpers/logPerformance'; import BrowserEnvironment from 'instances/browser_environment'; import Settings from 'controllers/settings'; import Auth from 'controllers/auth'; import ApplicationStore from 'stores/ApplicationStore'; import ModuleNavigationStore from 'stores/ModuleNavigationStore'; import ModuleNavigationActions from 'actions/ModuleNavigationActions'; import AuthActions from 'actions/AuthActions'; import LabActions from 'actions/LabActions'; import ChannelActions from 'actions/ChannelActions'; import Facebook from 'instances/facebook'; import zendesk from 'instances/zendesk'; import getUuid from 'helpers/uuid'; import ExperimentsActions from 'actions/ExperimentsActions'; import React, { Component } from 'react'; import Application from 'components/Application/Application'; import browserHistory from 'react-router/lib/browserHistory'; import { getItem, setItem } from 'helpers/localStorage'; // LinkClickHandler will listen to all clicks on links and handle/route them (pushState) require('helpers/linkclickhandler'); export default class ApplicationContainer extends Component { constructor() { super(); this.state = { status: ApplicationStore.getState().status, languageCode: i18n.getIso639_1(), user: Auth.getUser(), userAgent: { ...window.BrowserDetect, isDeprecated: BrowserEnvironment.isDeprecated(), }, }; } componentWillMount() { const uuid = getUuid(); Analytics.setSession(uuid); Analytics.track('Session', { browser: window.BrowserDetect.browser, device: window.BrowserDetect.device, os: window.BrowserDetect.operatingSystem, version: window.BrowserDetect.version, orientation: BrowserEnvironment.getOrientation(), app: window.BrowserDetect.app, appVersion: window.BrowserDetect.appVersion, standalone: navigator.standalone !== undefined ? navigator.standalone : 'unknown', }); } componentDidMount() { this._initFacebook(); this._initZendesk(); browserHistory.listen(this._onRoute.bind(this)); // Standlone (like on iOS added to desktop) remembers last URl visited // so on re-open the app starts at it last url if (navigator.standalone) { browserHistory.listen(this._rememberLastVisitedURL.bind(this)); } if (Settings.embedded) { window.parent.postMessage( { event: 'blendle.frame.hideclosebutton', }, Settings.embeddedOrigin, ); } i18n.on('initialized switch', (ev) => { this._setAnalyticsOrigin(ev); const languageCode = i18n.getIso639_1(); this.setState({ languageCode }); zendesk.execute('setLocale', languageCode); }); ApplicationStore.listen(() => { this.setState({ status: ApplicationStore.getState().status, }); }); // Load current application state from cookie ApplicationState.loadFromCookie(); this._run(); logPerformance.applicationRunning(); } _authHandler() { const user = Auth.getUser(); AuthActions.authenticateUser.defer(user); window.Raven.setTagsContext({ user_id: user.id }); Analytics.setUser(user); Country.setCountryCode(user.get('country')); i18n.load(user.get('primary_language')); i18n.setCurrency(user.get('currency')); ChannelActions.fetchChannels.defer(); zendesk.execute('identify', { name: user.get('full_name'), email: user.get('email'), organization: '', }); // Next tick to make sure experiments are synced setTimeout(() => this.setState({ user })); } _run() { if (Auth.getUser()) { this._authHandler(); } else { Auth.on('login', () => { this._authHandler(); }); } // Store the last visited url so we return to this on relaunch if (navigator.standalone) { browserHistory.replace(getItem('standaloneUrl')); } // Send the orientation to MixPanel when it changes. window.addEventListener('orientationchange', this._trackOrientation.bind(this)); Auth.on('logout', i18n.resetCookie); } _initFacebook() { // Init Facebook. Don't do anything if it failed here. If it failed we will // know in other places we use the lib. Handle fails there. Facebook.execute('init', { appId: Facebook.appId, version: Facebook.version, status: true, }); } _initZendesk() { zendesk.execute('setLocale', this.state.languageCode); zendesk.execute('setHelpCenterSuggestions', { url: true, labels: location.pathname.split('/'), }); } _rememberLastVisitedURL() { if (!window.BrowserDetect.localStorageEnabled()) { return; } let activeUrl = ModuleNavigationStore.getState().activeUrl; if (activeUrl === 'logout') { activeUrl = ''; } setItem('standaloneUrl', activeUrl); } _trackOrientation() { Analytics.track('Change orientation', { orientation: BrowserEnvironment.getOrientation(), location: ModuleNavigationStore.getState().activeUrl, }); } _onRoute(location) { Analytics.urlChange(); ModuleNavigationActions.setActiveUrl.defer(location.pathname); zendesk.execute('setHelpCenterSuggestions', { url: true, labels: location.pathname.split('/'), }); } _setAnalyticsOrigin() { Analytics.setOrigin(Country.getCountryCode(), i18n.getLocale()); } render() { return <Application {...this.state} {...this.props} />; } } // WEBPACK FOOTER // // ./src/js/app/containers/ApplicationContainer.js
app/javascript/mastodon/features/getting_started/components/announcements.js
abcang/mastodon
import React from 'react'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import Icon from 'mastodon/components/icon'; import { defineMessages, injectIntl, FormattedMessage, FormattedDate } from 'react-intl'; import { autoPlayGif, reduceMotion, disableSwiping } from 'mastodon/initial_state'; import elephantUIPlane from 'mastodon/../images/elephant_ui_plane.svg'; import { mascot } from 'mastodon/initial_state'; import unicodeMapping from 'mastodon/features/emoji/emoji_unicode_mapping_light'; import classNames from 'classnames'; import EmojiPickerDropdown from 'mastodon/features/compose/containers/emoji_picker_dropdown_container'; import AnimatedNumber from 'mastodon/components/animated_number'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { assetHost } from 'mastodon/utils/config'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, next: { id: 'lightbox.next', defaultMessage: 'Next' }, }); class Content extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { announcement: ImmutablePropTypes.map.isRequired, }; setRef = c => { this.node = c; } componentDidMount () { this._updateLinks(); } componentDidUpdate () { this._updateLinks(); } _updateLinks () { const node = this.node; if (!node) { return; } const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.announcement.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { let status = this.props.announcement.get('statuses').find(item => link.href === item.get('url')); if (status) { link.addEventListener('click', this.onStatusClick.bind(this, status), false); } link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/@${mention.get('acct')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, ''); if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/tags/${hashtag}`); } } onStatusClick = (status, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/@${status.getIn(['account', 'acct'])}/${status.get('id')}`); } } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } render () { const { announcement } = this.props; return ( <div className='announcements__item__content translate' ref={this.setRef} dangerouslySetInnerHTML={{ __html: announcement.get('contentHtml') }} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} /> ); } } class Emoji extends React.PureComponent { static propTypes = { emoji: PropTypes.string.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, hovered: PropTypes.bool.isRequired, }; render () { const { emoji, emojiMap, hovered } = this.props; if (unicodeMapping[emoji]) { const { filename, shortCode } = unicodeMapping[this.props.emoji]; const title = shortCode ? `:${shortCode}:` : ''; return ( <img draggable='false' className='emojione' alt={emoji} title={title} src={`${assetHost}/emoji/${filename}.svg`} /> ); } else if (emojiMap.get(emoji)) { const filename = (autoPlayGif || hovered) ? emojiMap.getIn([emoji, 'url']) : emojiMap.getIn([emoji, 'static_url']); const shortCode = `:${emoji}:`; return ( <img draggable='false' className='emojione custom-emoji' alt={shortCode} title={shortCode} src={filename} /> ); } else { return null; } } } class Reaction extends ImmutablePureComponent { static propTypes = { announcementId: PropTypes.string.isRequired, reaction: ImmutablePropTypes.map.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, style: PropTypes.object, }; state = { hovered: false, }; handleClick = () => { const { reaction, announcementId, addReaction, removeReaction } = this.props; if (reaction.get('me')) { removeReaction(announcementId, reaction.get('name')); } else { addReaction(announcementId, reaction.get('name')); } } handleMouseEnter = () => this.setState({ hovered: true }) handleMouseLeave = () => this.setState({ hovered: false }) render () { const { reaction } = this.props; let shortCode = reaction.get('name'); if (unicodeMapping[shortCode]) { shortCode = unicodeMapping[shortCode].shortCode; } return ( <button className={classNames('reactions-bar__item', { active: reaction.get('me') })} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} title={`:${shortCode}:`} style={this.props.style}> <span className='reactions-bar__item__emoji'><Emoji hovered={this.state.hovered} emoji={reaction.get('name')} emojiMap={this.props.emojiMap} /></span> <span className='reactions-bar__item__count'><AnimatedNumber value={reaction.get('count')} /></span> </button> ); } } class ReactionsBar extends ImmutablePureComponent { static propTypes = { announcementId: PropTypes.string.isRequired, reactions: ImmutablePropTypes.list.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, }; handleEmojiPick = data => { const { addReaction, announcementId } = this.props; addReaction(announcementId, data.native.replace(/:/g, '')); } willEnter () { return { scale: reduceMotion ? 1 : 0 }; } willLeave () { return { scale: reduceMotion ? 0 : spring(0, { stiffness: 170, damping: 26 }) }; } render () { const { reactions } = this.props; const visibleReactions = reactions.filter(x => x.get('count') > 0); const styles = visibleReactions.map(reaction => ({ key: reaction.get('name'), data: reaction, style: { scale: reduceMotion ? 1 : spring(1, { stiffness: 150, damping: 13 }) }, })).toArray(); return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <div className={classNames('reactions-bar', { 'reactions-bar--empty': visibleReactions.isEmpty() })}> {items.map(({ key, data, style }) => ( <Reaction key={key} reaction={data} style={{ transform: `scale(${style.scale})`, position: style.scale < 0.5 ? 'absolute' : 'static' }} announcementId={this.props.announcementId} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} emojiMap={this.props.emojiMap} /> ))} {visibleReactions.size < 8 && <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} button={<Icon id='plus' />} />} </div> )} </TransitionMotion> ); } } class Announcement extends ImmutablePureComponent { static propTypes = { announcement: ImmutablePropTypes.map.isRequired, emojiMap: ImmutablePropTypes.map.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, selected: PropTypes.bool, }; state = { unread: !this.props.announcement.get('read'), }; componentDidUpdate () { const { selected, announcement } = this.props; if (!selected && this.state.unread !== !announcement.get('read')) { this.setState({ unread: !announcement.get('read') }); } } render () { const { announcement } = this.props; const { unread } = this.state; const startsAt = announcement.get('starts_at') && new Date(announcement.get('starts_at')); const endsAt = announcement.get('ends_at') && new Date(announcement.get('ends_at')); const now = new Date(); const hasTimeRange = startsAt && endsAt; const skipYear = hasTimeRange && startsAt.getFullYear() === endsAt.getFullYear() && endsAt.getFullYear() === now.getFullYear(); const skipEndDate = hasTimeRange && startsAt.getDate() === endsAt.getDate() && startsAt.getMonth() === endsAt.getMonth() && startsAt.getFullYear() === endsAt.getFullYear(); const skipTime = announcement.get('all_day'); return ( <div className='announcements__item'> <strong className='announcements__item__range'> <FormattedMessage id='announcement.announcement' defaultMessage='Announcement' /> {hasTimeRange && <span> · <FormattedDate value={startsAt} hour12={false} year={(skipYear || startsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month='short' day='2-digit' hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /> - <FormattedDate value={endsAt} hour12={false} year={(skipYear || endsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month={skipEndDate ? undefined : 'short'} day={skipEndDate ? undefined : '2-digit'} hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /></span>} </strong> <Content announcement={announcement} /> <ReactionsBar reactions={announcement.get('reactions')} announcementId={announcement.get('id')} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} emojiMap={this.props.emojiMap} /> {unread && <span className='announcements__item__unread' />} </div> ); } } export default @injectIntl class Announcements extends ImmutablePureComponent { static propTypes = { announcements: ImmutablePropTypes.list, emojiMap: ImmutablePropTypes.map.isRequired, dismissAnnouncement: PropTypes.func.isRequired, addReaction: PropTypes.func.isRequired, removeReaction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { index: 0, }; static getDerivedStateFromProps(props, state) { if (props.announcements.size > 0 && state.index >= props.announcements.size) { return { index: props.announcements.size - 1 }; } else { return null; } } componentDidMount () { this._markAnnouncementAsRead(); } componentDidUpdate () { this._markAnnouncementAsRead(); } _markAnnouncementAsRead () { const { dismissAnnouncement, announcements } = this.props; const { index } = this.state; const announcement = announcements.get(announcements.size - 1 - index); if (!announcement.get('read')) dismissAnnouncement(announcement.get('id')); } handleChangeIndex = index => { this.setState({ index: index % this.props.announcements.size }); } handleNextClick = () => { this.setState({ index: (this.state.index + 1) % this.props.announcements.size }); } handlePrevClick = () => { this.setState({ index: (this.props.announcements.size + this.state.index - 1) % this.props.announcements.size }); } render () { const { announcements, intl } = this.props; const { index } = this.state; if (announcements.isEmpty()) { return null; } return ( <div className='announcements'> <img className='announcements__mastodon' alt='' draggable='false' src={mascot || elephantUIPlane} /> <div className='announcements__container'> <ReactSwipeableViews animateHeight={!reduceMotion} adjustHeight={reduceMotion} index={index} onChangeIndex={this.handleChangeIndex}> {announcements.map((announcement, idx) => ( <Announcement key={announcement.get('id')} announcement={announcement} emojiMap={this.props.emojiMap} addReaction={this.props.addReaction} removeReaction={this.props.removeReaction} intl={intl} selected={index === idx} disabled={disableSwiping} /> )).reverse()} </ReactSwipeableViews> {announcements.size > 1 && ( <div className='announcements__pagination'> <IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.previous)} icon='chevron-left' onClick={this.handlePrevClick} size={13} /> <span>{index + 1} / {announcements.size}</span> <IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.next)} icon='chevron-right' onClick={this.handleNextClick} size={13} /> </div> )} </div> </div> ); } }
classic/src/scenes/wbui/SleepableField.js
wavebox/waveboxapp
import PropTypes from 'prop-types' import React from 'react' import shallowCompare from 'react-addons-shallow-compare' import { FormControl, Input, InputLabel, InputAdornment, Checkbox, Grid } from '@material-ui/core' import { withStyles } from '@material-ui/core/styles' const styles = { gridContainer: { marginTop: 10 }, checkboxGridItem: { height: 56 }, numberGridItem: { height: 56, flex: 1 }, checkbox: { width: 20 }, numberInput: { marginTop: 8 } } @withStyles(styles) class SleepableField extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { disabled: PropTypes.bool.isRequired, sleepEnabled: PropTypes.bool.isRequired, onSleepEnabledChanged: PropTypes.func.isRequired, sleepWaitMs: PropTypes.number.isRequired, onSleepWaitMsChanged: PropTypes.func.isRequired } static defaultProps = { disabled: false } /* **************************************************************************/ // Component lifecycle /* **************************************************************************/ componentWillReceiveProps (nextProps) { if (this.props.sleepWaitMs !== nextProps.sleepWaitMs) { this.setState({ intermediaryValue: `${this.humanizeMillis(nextProps.sleepWaitMs)}` }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { return { intermediaryValue: `${this.humanizeMillis(this.props.sleepWaitMs)}` } })() /** * @param millis: the millis to humanize * @return a nicer value */ humanizeMillis (millis) { return Math.round(((millis / 1000) / 60) * 10) / 10 } /* **************************************************************************/ // UI Events /* **************************************************************************/ /** * Finishes editing the sleep wait millis by converting to a safe number and emitting */ finishEditingSleepWaitMs () { const valueFloat = parseFloat(this.state.intermediaryValue) if (isNaN(valueFloat)) { this.setState({ intermediaryValue: `${this.humanizeMillis(this.props.sleepWaitMs)}` }) } else { const value = valueFloat * 1000 * 60 if (value !== this.props.sleepWaitMs) { this.props.onSleepWaitMsChanged(value) } } } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { disabled, sleepEnabled, onSleepEnabledChanged, sleepWaitMs, onSleepWaitMsChanged, classes, ...passProps } = this.props const { intermediaryValue } = this.state return ( <FormControl {...passProps}> <InputLabel>Sleep tab after minutes of inactivity</InputLabel> <Grid className={classes.gridContainer} container spacing={8} alignItems='flex-end'> <Grid className={classes.checkboxGridItem} item> <Checkbox className={classes.checkbox} color='primary' disabled={disabled} checked={sleepEnabled} onChange={(evt, toggled) => { onSleepEnabledChanged(toggled) }} /> </Grid> <Grid className={classes.numberGridItem} item> <Input className={classes.numberInput} type='number' min='0' step='0.5' placeholder='1.5' fullWidth disabled={disabled || !sleepEnabled} value={intermediaryValue} onChange={(evt) => { this.setState({ intermediaryValue: evt.target.value }) }} onBlur={(evt) => { this.finishEditingSleepWaitMs() }} endAdornment={<InputAdornment position='end'>minutes</InputAdornment>} /> </Grid> </Grid> </FormControl> ) } } export default SleepableField
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ComputedProperties.js
matart15/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(prefix) { return [ { id: 1, [`${prefix} name`]: '1' }, { id: 2, [`${prefix} name`]: '2' }, { id: 3, [`${prefix} name`]: '3' }, { id: 4, [`${prefix} name`]: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load('user_'); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-computed-properties"> {this.state.users.map(user => ( <div key={user.id}>{user.user_name}</div> ))} </div> ); } }
containers/AddTodo.js
jpsierens/react-redux-todo
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' const handleInput = (input, onAdd) => { onAdd(input.value) input.value = '' } let AddTodo = ({ onAdd }) => { let input return ( <div> <input ref={node => { input = node }} onKeyPress={(e) => { if (e.key === "Enter") { handleInput(input, onAdd) } }} /> <button onClick={() => handleInput(input, onAdd)}> Add Todo </button> </div> ) } const mapDispatchToProps = (dispatch) => { return { onAdd: value => dispatch(addTodo(value)) } } AddTodo = connect( () => {return {}}, mapDispatchToProps )(AddTodo) export default AddTodo
client/knowledge_base_search/src/index.js
watson-developer-cloud/discovery-starter-kit
/* eslint-disable react/jsx-filename-extension */ import 'phantomjs-polyfill-find-index/findIndex-polyfill'; import 'phantomjs-polyfill-find/find-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.getElementById('root'), );
gadget-system-teamwork/src/index.js
TeodorDimitrov89/JS-Web-Teamwork-2017
import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from 'react-router-dom' import './index.css' import App from './App' import registerServiceWorker from './registerServiceWorker' ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root')) registerServiceWorker()
definitions/npm/styled-components_v3.x.x/flow_v0.104.x-/test_styled-components_v3.x.x.js
flowtype/flow-typed
// @flow import {renderToString} from 'react-dom/server' import styled, { css, ThemeProvider, withTheme, keyframes, ServerStyleSheet, StyleSheetManager } from 'styled-components' import React from 'react' import type { Theme, Interpolation, ReactComponentFunctional, ReactComponentFunctionalUndefinedDefaultProps, ReactComponentClass, ReactComponentStyled, ReactComponentStyledTaggedTemplateLiteral, ReactComponentUnion, ReactComponentIntersection, } from 'styled-components' import { createReadStream } from 'fs' const TitleTaggedTemplateLiteral: ReactComponentStyledTaggedTemplateLiteral<{...}> = styled.h1; const TitleStyled: ReactComponentStyled<any> = styled.h1` font-size: 1.5em; `; const TitleGeneric: ReactComponentIntersection<any> = styled.h1` font-size: 1.5em; `; `` const TitleFunctional: ReactComponentFunctional<any> = styled.h1` font-size: 1.5em; `; const TitleClass: ReactComponentClass<any> = styled.h1` font-size: 1.5em; `; declare var needsReactComponentFunctional: ReactComponentFunctional<any> => void declare var needsReactComponentClass: ReactComponentClass<any> => void needsReactComponentFunctional(TitleStyled) needsReactComponentClass(TitleStyled) const ExtendedTitle: ReactComponentIntersection<any> = styled(TitleStyled)` font-size: 2em; `; const Wrapper: ReactComponentIntersection<any> = styled.section` padding: 4em; background: ${({theme}) => theme.background}; `; // ---- EXTEND ---- const Attrs0ReactComponent: ReactComponentStyled<any> = styled.div.extend``; const Attrs0ExtendReactComponent: ReactComponentIntersection<any> = Attrs0ReactComponent.extend``; const Attrs0SyledComponent: ReactComponentStyledTaggedTemplateLiteral<any> = styled.div; const Attrs0ExtendStyledComponent: ReactComponentIntersection<any> = Attrs0SyledComponent.extend``; // ---- ATTRIBUTES ---- const Attrs1: ReactComponentStyledTaggedTemplateLiteral<any> = styled.section.attrs({ testProp: 'foo' }); // $FlowExpectedError const Attrs1Error: ReactComponentStyledTaggedTemplateLiteral<any> = styled.section.attrs({ testProp: 'foo' })``; declare var needsString: string => void needsReactComponentFunctional(styled.section.attrs({})``) needsReactComponentClass(styled.section.attrs({})``) // $FlowExpectedError needsString(styled.section.attrs({})``) const Attrs2: ReactComponentStyledTaggedTemplateLiteral<any> = styled.section .attrs({ testProp1: 'foo' }) .attrs({ testProp2: 'bar' }); const Attrs3Styled: ReactComponentStyled<any> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Generic: ReactComponentIntersection<any> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Functional: ReactComponentFunctional<any> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const Attrs3Class: ReactComponentClass<any> = styled.section.attrs({ testProp: 'foo' })` background-color: red; `; const theme: Theme = { background: "papayawhip" }; // ---- WithComponent ---- const withComponent1: ReactComponentStyled<any> = styled.div.withComponent('a'); const withComponent2: ReactComponentStyled<any> = styled.div.withComponent(withComponent1); const withComponent3: ReactComponentStyled<any> = styled.div.withComponent(Attrs3Class); const withComponent4: ReactComponentStyled<any> = styled('div').withComponent('a'); const withComponent5: ReactComponentStyled<any> = styled('div').withComponent(withComponent1); const withComponent6: ReactComponentStyled<any> = styled('div').withComponent(Attrs3Class); // $FlowExpectedError const withComponentError1: ReactComponentStyled<any> = styled.div.withComponent(0); // $FlowExpectedError const withComponentError2: ReactComponentStyled<any> = styled.div.withComponent('NotHere'); class CustomComponentError3 extends React.Component<{ foo: string, ... }> { render() { return <div />; } } // $FlowExpectedError const withComponentError3 = styled(CustomComponentError3).withComponent('a'); // $FlowExpectedError const withComponentError4 = styled(CustomComponentError3).withComponent(withComponent1); // $FlowExpectedError const withComponentError5 = styled(CustomComponentError3).withComponent(Attrs3Class); // $FlowExpectedError const withComponentError6 = styled(CustomComponentError3).withComponent(0); // $FlowExpectedError const withComponentError7 = styled(CustomComponentError3).withComponent('NotHere'); // ---- WithTheme ---- const Component: ReactComponentFunctionalUndefinedDefaultProps<{ theme: Theme, ... }> = ({ theme }) => ( <ThemeProvider theme={theme}> <Wrapper> <TitleStyled>Hello World, this is my first styled component!</TitleStyled> </Wrapper> </ThemeProvider> ); const ComponentWithTheme: ReactComponentFunctionalUndefinedDefaultProps<{...}> = withTheme(Component); const Component2: ReactComponentFunctionalUndefinedDefaultProps<{...}> = () => ( <ThemeProvider theme={outerTheme => outerTheme}> <Wrapper> <TitleStyled>Hello World, this is my first styled component!</TitleStyled> </Wrapper> </ThemeProvider> ); const OpacityKeyFrame: string = keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; // $FlowExpectedError const NoExistingElementWrapper = styled.nonexisting` padding: 4em; background: papayawhip; `; const num: 9 = 9 // $FlowExpectedError const NoExistingComponentWrapper = styled()` padding: 4em; background: papayawhip; `; // $FlowExpectedError const NumberWrapper = styled(num)` padding: 4em; background: papayawhip; `; const sheet = new ServerStyleSheet() const html = renderToString(sheet.collectStyles(<ComponentWithTheme />)) const css1 = sheet.getStyleTags() const sheet2 = new ServerStyleSheet() const html2 = renderToString( <StyleSheetManager sheet={sheet}> <ComponentWithTheme /> </StyleSheetManager> ) const css2 = sheet.getStyleTags() const css3 = sheet.getStyleElement() const stream = createReadStream('file.txt') // $FlowExpectedError (Must pass in a readable stream) sheet.interleaveWithNodeStream('file.txt') sheet.interleaveWithNodeStream(stream) // ---- COMPONENT CLASS TESTS ---- class NeedsThemeReactClass extends React.Component<{ foo: string, theme: Theme, ... }> { render() { return <div />; } } class ReactClass extends React.Component<{ foo: string, ... }> { render() { return <div />; } } const StyledClass: ReactComponentClass<{ foo: string, theme: Theme, ... }> = styled(NeedsThemeReactClass)` color: red; `; // ---- INTERPOLATION TESTS ---- const interpolation: Array<Interpolation> = styled.css` background-color: red; `; const interpolation2: Array<Interpolation> = css` background-color: red; `; // $FlowExpectedError const interpolationError: Array<Interpolation | boolean> = styled.css` background-color: red; `; // $FlowExpectedError const interpolationError2: Array<Interpolation | boolean> = css` background-color: red; `; // ---- DEFAULT COMPONENT TESTS ---- const defaultComponent: ReactComponentIntersection<{...}> = styled.div` background-color: red; `; // $FlowExpectedError const defaultComponentError: {...} => string = styled.div` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS ---- const FunctionalComponent: ReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: Theme, ... }> = props => <div />; const NeedsFoo1: ReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: Theme, ... }> = styled(FunctionalComponent)` background-color: red; `; // $FlowExpectedError const NeedsFoo1Error: ReactComponentFunctionalUndefinedDefaultProps<{ foo: number, ... }> = styled(FunctionalComponent)` background-color: red; `; const NeedsFoo2: ReactComponentFunctionalUndefinedDefaultProps<{ foo: string, theme: Theme, ... }> = styled(NeedsFoo1)` background-color: red; `; // $FlowExpectedError const NeedsFoo2Error: ReactComponentFunctionalUndefinedDefaultProps<{ foo: number, ... }> = styled(NeedsFoo1)` background-color: red; `; const NeedsNothingInferred = styled(() => <div />);
src/library/modal/index.js
zdizzle6717/universal-react-movie-app
'use strict'; import React from 'react'; import classNames from 'classnames'; import Animation from 'react-addons-css-transition-group'; export default class Modal extends React.Component { constructor(props, context) { super(props, context); } render() { let containerClasses = classNames({ 'modal-container': true, 'show': this.props.modalIsOpen }) let backdropClasses = classNames({ 'modal-backdrop': true, 'show': this.props.modalIsOpen }) return ( <div className={containerClasses} key={this.props.name}> <Animation transitionName="slide-z" className="modal-animation-wrapper" transitionAppear={true} transitionAppearTimeout={500} transitionEnter={true} transitionEnterTimeout={500} transitionLeave={true} transitionLeaveTimeout={500}> { this.props.modalIsOpen && <div className="modal"> <div className="modal-content"> <div className="panel"> <div className="panel-title primary"> {this.props.title} </div> <div className="panel-content"> {this.props.children} </div> <div className="panel-footer text-right"> <button type="button collapse" className="button alert" onClick={this.props.handleClose}>Cancel</button> <button type="button collapse" className="button success" onClick={this.props.handleSubmit}>Submit</button> </div> </div> </div> </div> } </Animation> <div className={backdropClasses} onClick={this.props.handleClose}></div> </div> ); } } Modal.propTypes = { name: React.PropTypes.string.isRequired, title: React.PropTypes.string.isRequired, handleClose: React.PropTypes.func.isRequired, handleSubmit: React.PropTypes.func.isRequired, modalIsOpen: React.PropTypes.bool.isRequired }
src/js/components/icons/base/Transaction.js
odedre/grommet-final
/** * @description Transaction SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M2,7 L20,7 M16,2 L21,7 L16,12 M22,17 L4,17 M8,12 L3,17 L8,22"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-transaction`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'transaction'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M2,7 L20,7 M16,2 L21,7 L16,12 M22,17 L4,17 M8,12 L3,17 L8,22"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Transaction'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
actor-apps/app-web/src/app/components/modals/Preferences.react.js
liruqi/actor-platform
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import PreferencesStore from 'stores/PreferencesStore'; const appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); const ThemeManager = new Styles.ThemeManager(); const menuItems = [ { payload: '1', text: 'English', value: 'en'}, { payload: '2', text: 'Russian', value: 'ru'} ]; const getStateFromStores = () => { const language = PreferencesStore.language; return { isOpen: PreferencesStore.isModalOpen, preferences: PreferencesStore.preferences, language: language, selectedLanguage: _.findIndex(menuItems, {value: language}) }; }; @ReactMixin.decorate(IntlMixin) class PreferencesModal extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = getStateFromStores(); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); PreferencesStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { PreferencesStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { PreferencesActionCreators.hide(); }; onDone = () => { PreferencesActionCreators.save({ language: this.state.language, sendByEnter: this.refs.sendByEnter.getSelectedValue() }); this.onClose(); }; onKeyDown = event => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onLanguageChange = (event, selectedIndex, menuItem) => { this.setState({ language: menuItem.value, selectedLanguage: _.findIndex(menuItems, {value: menuItem.value}) }); }; render() { const preferences = this.state.preferences; if (this.state.isOpen === true) { return ( <Modal className="modal-new modal-new--preferences" closeTimeoutMS={150} isOpen={this.state.isOpen} style={{width: 760}}> <div className="modal-new__header"> <i className="modal-new__header__icon material-icons">settings</i> <h3 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/> </h3> <div className="pull-right"> <FlatButton hoverColor="rgba(81,145,219,.17)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onDone} secondary={true} style={{marginTop: -6}}/> </div> </div> <div className="modal-new__body"> <div className="preferences"> <aside className="preferences__tabs"> <a className="preferences__tabs__tab preferences__tabs__tab--active">General</a> <a className="preferences__tabs__tab hide">Notifications</a> <a className="preferences__tabs__tab hide">Sidebar colors</a> <a className="preferences__tabs__tab hide">Security</a> <a className="preferences__tabs__tab hide">Other Options</a> </aside> <div className="preferences__body"> <div className="preferences__list"> <div className="preferences__list__item preferences__list__item--general"> <ul> <li> <i className="icon material-icons">keyboard</i> <RadioButtonGroup defaultSelected={preferences.sendByEnter} name="send" ref="sendByEnter"> <RadioButton label="Enter – send message, Shift + Enter – new line" style={{marginBottom: 12}} value="true"/> <RadioButton label="Cmd + Enter – send message, Enter – new line" value="false"/> </RadioButtonGroup> </li> <li className="language hide"> <i className="icon material-icons">menu</i> Language: <DropDownMenu labelStyle={{color: '#5191db'}} menuItemStyle={{height: '40px', lineHeight: '40px'}} menuItems={menuItems} onChange={this.onLanguageChange} selectedIndex={this.state.selectedLanguage} style={{verticalAlign: 'top', height: 52}} underlineStyle={{display: 'none'}}/> </li> </ul> </div> <div className="preferences__list__item preferences__list__item--notifications hide"> <ul> <li> <i className="icon material-icons">notifications</i> <RadioButtonGroup defaultSelected="all" name="notifications"> <RadioButton label="Notifications for activity of any kind" style={{marginBottom: 12}} value="all"/> <RadioButton label="Notifications for Highlight Words and direct messages" style={{marginBottom: 12}} value="quiet"/> <RadioButton label="Never send me notifications" style={{marginBottom: 12}} value="disable"/> </RadioButtonGroup> <p className="hint"> You can override your desktop notification preference on a case-by-case basis for channels and groups from the channel or group menu. </p> </li> </ul> </div> </div> </div> </div> </div> </Modal> ); } else { return null; } } } export default PreferencesModal;
test/helpers/shallowRenderHelper.js
xbili/iwastetime2
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
admin/client/components/ItemsTableValue.js
stunjiturner/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; var ItemsTableValue = React.createClass({ displayName: 'ItemsTableValue', propTypes: { className: React.PropTypes.string, exterior: React.PropTypes.bool, field: React.PropTypes.string, href: React.PropTypes.string, interior: React.PropTypes.bool, padded: React.PropTypes.bool, truncate: React.PropTypes.bool, }, getDefaultProps () { return { truncate: true, }; }, render () { let tag = this.props.href ? 'a' : 'div'; let className = classnames('ItemList__value', ( this.props.field ? ('ItemList__value--' + this.props.field) : null ), { 'ItemList__value--truncate': this.props.truncate, 'ItemList__link--empty': this.props.empty, 'ItemList__link--exterior': this.props.href && this.props.exterior, 'ItemList__link--interior': this.props.href && this.props.interior, 'ItemList__link--padded': this.props.href && this.props.padded, }, this.props.className); var props = blacklist(this.props, 'children', 'className', 'exterior', 'field', 'interior', 'padded'); props.className = className; return React.createElement( tag, props, this.props.children ); } }); module.exports = ItemsTableValue;
src/components/index.js
lnrd256/twitter_client
import React, { Component } from 'react'; import {reduxForm} from 'redux-form'; import FormUser from '../containers/form-user'; export default class Index extends Component { render() { return ( <div> <div className="container white login"> <FormUser/> </div> </div> ); } }
src/components/NotFoundPage.js
rafurr/react-material-ui-components
import React from 'react'; import {Link} from 'react-router'; // Since this component is simple and static, there's no parent container for it. const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
src/components/Footer/FacebookIcon.js
Galernaya20/galernaya20.com
//@flow import React from 'react' import {Svg} from '../Svg/Svg' export const FacebookIcon = (props: Object) => ( <Svg {...props}> <path d="M41,4H9C6.24,4,4,6.24,4,9v32c0,2.76,2.24,5,5,5h32c2.76,0,5-2.24,5-5V9C46,6.24,43.76,4,41,4z M37,19h-2c-2.14,0-3,0.5-3,2 v3h5l-1,5h-4v15h-5V29h-4v-5h4v-3c0-4,2-7,6-7c2.9,0,4,1,4,1V19z" /> </Svg> )
src/bundles/ApplicationsAdmin/BriefAdminWidget.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import { Provider } from 'react-redux' import { Route, Switch } from 'react-router-dom'; import RegisterComponent from '../../RegisterComponent' import createStore from './redux/create' import BriefEdit from './components/BriefEdit' const BriefAdminWidget = (props) => { const store = createStore(props); return ( <Provider store={store} > <Switch> <Route path="/admin/buyers/:id/edit" component={BriefEdit} /> </Switch> </Provider> ) } export default new RegisterComponent({ 'brief-admin': BriefAdminWidget })
server/frontend/src/components/ManageForm/manageForm.js
cs472-spots/spots
import React from 'react'; class SearchForm extends React.Component { constructor (props) { super(props); this.state = { info: { firstName: '' } } } render() { const { info } = this.props; return ( <div className="row"> {/* Left column */} <div className="col-md-6"> {/* General Information Form */} <div className="box box-primary"> {/* General Information */} <div className="box-header"> <h3 className="box-title">General Information</h3> </div> {/* Form starts here */} <form role="form"> <div className="box-body"> {/* Name */} <div className="form-group"> <label>First Name</label> <input type="text" className="form-control" placeholder="First Name" name="firstName" value={info.firstName} onChange={this.props.userChange}></input> </div> {/* LastName */} <div className="form-group"> <label>Last Name</label> <input type="text" className="form-control" placeholder="Last Name" name="lastName" value={info.lastName} onChange={this.props.userChange}></input> </div> {/* Address */} {/*Add Address field to database <div className="form-group"> <label>Address</label> <input type="text" className="form-control" placeholder="Address" readOnly></input> </div>*/} {/* City and Zip*/} {/* Add City and Zip to databse <div className="form-group"> <label>City, Zip</label> <input type="text" className="form-control" placeholder="City, Zip" readOnly></input> </div>*/} {/* NSHE ID # */} <div className="form-group"> <label>NSHE ID</label> <input type="text" className="form-control" placeholder="NSHE" name="userID" value={info.userID} onChange={this.props.userChange}></input> </div> {/* E-mail address*/} <div className="form-group"> <label>Email</label> <input type="text" className="form-control" placeholder="Email" name="email" value={info.email} onChange={this.props.userChange}></input> </div> {/* Phone # */} <div className="form-group"> <label>Phone #</label> <input type="text" className="form-control" placeholder="Phone Number" name="phone" value={info.phone} onChange={this.props.userChange}></input> </div> </div> </form> </div> {/* For Office Use Only Form */} <div className="box box-office-use"> {/* For Office Use Only */} <div className="box-header"> <h3 className="box-title">For Office Use Only</h3> </div> {/* Form starts here */} <form role="form"> <div className="box-body"> {/* Parking Sticker # */} <div className="form-group"> <label>Card ID #</label> <input type="text" className="form-control" placeholder="Card ID #" name="cardid" value={info.cardid} onChange={this.props.userChange}></input> </div> {/* Type Of Sticker */} <div className="form-group"> <label>Permit Type</label> <input type="text" className="form-control" placeholder="Permit Type" name="permitType" value={info.permitType} onChange={this.props.userChange}></input> </div> {/* Semester */} {/*Add Semester field to database <div className="form-group"> <label>Semester</label> <input type="text" className="form-control" readOnly placeholder="Semester"></input> </div>*/} </div> </form> </div> </div> {/* ===================================================* /} {/* Left Column */} <div className="col-md-6"> {/* Vehicle Information Form */} <div className="box box-car "> {/* Vehicle Information */} <div className="box-header"> <h3 className="box-title">Vehicle Information</h3> </div> {/* Form starts here */} <form role="form"> <div className="box-body"> {/* Year */} <div className="form-group"> <label>Year</label> <input type="text" className="form-control" placeholder="Year" name="v1_year" /*value={info.v1_year}*/ onChange={this.props.userChange}></input> </div> {/* Make */} <div className="form-group"> <label>Make</label> <input type="text" className="form-control" placeholder="Make" name="v1_make" value={info.v1_make} onChange={this.props.userChange}></input> </div> {/* Model */} <div className="form-group"> <label>Model</label> <input type="text" className="form-control" placeholder="Model" name="v1_model" value={info.v1_model} onChange={this.props.userChange}></input> </div> {/* Color */} <div className="form-group"> <label>Color</label> <input type="text" className="form-control" placeholder="Color" name="v1_color" value={info.v1_color} onChange={this.props.userChange}></input> </div> {/* License Plate # */} <div className="form-group"> <label>License Plate #</label> <input type="text" className="form-control" placeholder="License Plate Number" name="v1_plate" value={info.v1_plate} onChange={this.props.userChange}></input> </div> </div> </form> </div> </div> </div> ); } } export default SearchForm;
examples/huge-apps/routes/Grades/components/Grades.js
ryardley/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
docs/src/app/components/pages/components/FontIcon/ExampleIcons.js
ichiohta/material-ui
import React from 'react'; import FontIcon from 'material-ui/FontIcon'; import {red500, yellow500, blue500} from 'material-ui/styles/colors'; const iconStyles = { marginRight: 24, }; const FontIconExampleIcons = () => ( <div> <FontIcon className="material-icons" style={iconStyles}>home</FontIcon> <FontIcon className="material-icons" style={iconStyles} color={red500}>flight_takeoff</FontIcon> <FontIcon className="material-icons" style={iconStyles} color={yellow500}>cloud_download</FontIcon> <FontIcon className="material-icons" style={iconStyles} color={blue500}>videogame_asset</FontIcon> </div> ); export default FontIconExampleIcons;
src/components/views/items/CarouselMixAlbums.js
planlodge/soundmix
import React from 'react'; import {NavLink} from 'react-router-dom'; import OwlCarousel from 'react-owl-carousel'; // Using "Stateless Functional Components" export default function (props) { //console.log("Ps", props); return ( <OwlCarousel items={6} autoplaySpeed={300} lazyLoad={true} rewind={true} margin={0} navText={['<i class="material-icons">skip_previous</i>','<i class="material-icons">skip_next</i>']} nav responsive={ { "0": {items: 1}, "500": {items: 3}, "1000": {items: 5} } } autoplay={true} autoplayHoverPause={true}> {props.list.map((item, i) => { return ( <div key={i} className="col s12"> <div className="item card hoverable carouselCard carouselCardMixAlbum"> <div className="card-image"> <NavLink to={"/mix" + item.key}> <img src={item.pictures.large} alt={item.name}/> <span className="card-title small">{item.name}</span> </NavLink> </div> </div> </div> ); })} </OwlCarousel> ); }
src/layouts/PaymentLayout/PaymentLayout.js
bruceli1986/contract-react
import React from 'react' import PaymentToolbar from '../../components/PaymentToolbar' import Nav from '../../containers/basic/Nav' import PaymentFooter from '../../components/PaymentFooter' import '../../styles/layout/paymentlayout.scss' import '../../styles/icon.scss' import { translate } from 'react-i18next' /** 合同支付布局*/ class PaymentLayout extends React.Component { static propTypes = { children: React.PropTypes.element } constructor (props, context) { super(props, context) this.state = { loginUser: {} } } fetchUser () { this.serverRequest = $.get('/qdp/login/user?' + new Date().getTime(), function (result) { this.setState({ 'loginUser': result }) }.bind(this)) } fetchTaskCount () { $.get('/qdp/payment/bpm/task/count/todoTask?data=' + new Date().getTime(), function (result) { var toolbarBtns = [{ tip: '我的待办', url: '/taskManage/todoTask', icon: 'glyphicon-tasks', split: true, badge: result }, { tip: '查看合同', url: '/contract/view', icon: 'glyphicon-search' }] this.setState({toolbarBtns: toolbarBtns}) }.bind(this)) } componentDidMount () { this.fetchUser() this.fetchTaskCount() } render () { const { t } = this.props let pages = [{ url: '/taskManage/todoTask', title: t('TaskCenter'), children: [{ url: '/taskManage/todoTask', title: '待办事项' }, { url: '/taskManage/passTask', title: '经办事项' }, { url: '/taskManage/historyTask', title: '办结事项' }, { url: '/taskManage/participantTask', title: '关注事项' }] }, { url: '/contract/view', title: '合同业务' }] return ( <div className='site'> <PaymentToolbar btns={this.state.toolbarBtns} /> <Nav /> <div className='site-content'> {this.props.children && React.cloneElement(this.props.children, {loginUser: this.stateloginUser})} </div> <PaymentFooter /> </div> ) } } export default translate(['common'], {withRef: true})(PaymentLayout)
src/Parser/Druid/Guardian/Modules/Features/AntiFillerSpam.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import EnemyInstances from 'Parser/Core/Modules/EnemyInstances'; import SpellUsable from 'Parser/Core/Modules/SpellUsable'; import GlobalCooldown from 'Parser/Core/Modules/GlobalCooldown'; import StatisticBox from 'Main/StatisticBox'; import Abilities from '../Abilities'; import ActiveTargets from './ActiveTargets'; const debug = false; // Determines whether a variable is a function or not, and returns its value function resolveValue(maybeFunction, ...args) { if (typeof maybeFunction === 'function') { return maybeFunction(...args); } return maybeFunction; } class AntiFillerSpam extends Analyzer { static dependencies = { combatants: Combatants, enemyInstances: EnemyInstances, activeTargets: ActiveTargets, spellUsable: SpellUsable, globalCooldown: GlobalCooldown, abilities: Abilities, }; abilityLastCasts = {}; _totalGCDSpells = 0; _totalFillerSpells = 0; _unnecessaryFillerSpells = 0; on_byPlayer_cast(event) { const spellId = event.ability.guid; const ability = this.abilities.getAbility(spellId); if (!ability || !ability.isOnGCD) { return; } this._totalGCDSpells += 1; const timestamp = event.timestamp; const spellLastCast = this.abilityLastCasts[spellId] || -Infinity; const targets = this.activeTargets.getActiveTargets(event.timestamp).map(enemyID => this.enemyInstances.enemies[enemyID]).filter(enemy => !!enemy); const combatant = this.combatants.selected; this.abilityLastCasts[spellId] = timestamp; let isFiller = false; if (ability.antiFillerSpam) { if (typeof ability.antiFillerSpam.isFiller === 'function') { isFiller = ability.antiFillerSpam.isFiller(event, combatant, targets, spellLastCast); } else { isFiller = ability.antiFillerSpam.isFiller; } } if (!isFiller) { return; } debug && console.group(`[FILLER SPELL] - ${spellId} ${SPELLS[spellId].name}`); this._totalFillerSpells += 1; const availableSpells = []; // Only abilities on the GCD matter since the goal is to make sure every GCD is used as efficiently as possible this.globalCooldown.abilitiesOnGlobalCooldown .map(spellId => this.abilities.getAbility(spellId)) .filter(ability => ability !== null) .forEach(gcdSpell => { const gcdSpellId = gcdSpell.primarySpell.id; if (ability.primarySpell.id === gcdSpellId) { return; } const lastCast = this.abilityLastCasts[gcdSpellId] || -Infinity; const isFillerEval = gcdSpell.antiFillerSpam && (typeof gcdSpell.antiFillerSpam.isFiller === 'function' ? gcdSpell.antiFillerSpam.isFiller(event, combatant, targets, lastCast) : gcdSpell.antiFillerSpam.isFiller); if (isFillerEval || gcdSpell.category === Abilities.SPELL_CATEGORIES.UTILITY) { return; } const isOffCooldown = this.spellUsable.isAvailable(gcdSpellId); const args = [event, combatant, targets, lastCast]; const meetsCondition = (gcdSpell.antiFillerSpam.condition !== undefined) ? resolveValue(gcdSpell.antiFillerSpam.condition, ...args) : true; if (!meetsCondition) { return; } if (!isOffCooldown) { return; } debug && console.warn(` [Available non-filler] - ${gcdSpellId} ${SPELLS[gcdSpellId].name} - offCD: ${isOffCooldown} - canBeCast: ${meetsCondition} `); availableSpells.push(gcdSpellId); }); if (availableSpells.length > 0) { this._unnecessaryFillerSpells += 1; } debug && console.groupEnd(); } get fillerSpamPercentage() { return this._unnecessaryFillerSpells / this._totalGCDSpells; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SWIPE_BEAR.id} />} value={`${formatPercentage(this.fillerSpamPercentage)}%`} label="Unnecessary Fillers" tooltip={`You cast <strong>${this._unnecessaryFillerSpells}</strong> unnecessary filler spells out of <strong>${this._totalGCDSpells}</strong> total GCDs. Filler spells (Swipe, Moonfire without a GG proc, or Moonfire outside of pandemic if talented into Incarnation) do far less damage than your main rotational spells, and should be minimized whenever possible.`} /> ); } suggestions(when) { when(this.fillerSpamPercentage).isGreaterThan(0.1) .addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> You are casting too many unnecessary filler spells. Try to plan your casts two or three GCDs ahead of time to anticipate your main rotational spells coming off cooldown, and to give yourself time to react to <SpellLink id={SPELLS.GORE_BEAR.id} /> and <SpellLink id={SPELLS.GALACTIC_GUARDIAN_TALENT.id} /> procs. </Wrapper> ) .icon(SPELLS.SWIPE_BEAR.icon) .actual(`${formatPercentage(actual)}% unnecessary filler spells cast`) .recommended(`${formatPercentage(recommended, 0)}% or less is recommended`) .regular(recommended + 0.05).major(recommended + 0.1); }); } } export default AntiFillerSpam;
react-router-tutorial/lessons/10-clean-urls/modules/Repo.js
zerotung/practices-and-notes
import React from 'react' export default React.createClass({ render() { return ( <div> <h2>{this.props.params.repoName}</h2> </div> ) } })
src/workflows/visualizer/components/steps/Visualization/Start.js
Kitware/HPCCloud
import React from 'react'; import JobSubmission from '../../../../generic/components/steps/JobSubmission'; // ---------------------------------------------------------------------------- const actionList = [ { name: 'prepareJob', label: 'Start Visualization', icon: '' }, ]; // ---------------------------------------------------------------------------- function clusterFilter(cluster) { return ( 'config' in cluster && 'paraview' in cluster.config && 'installDir' in cluster.config.paraview && cluster.config.paraview.installDir ); } // ---------------------------------------------------------------------------- function getTaskflowMetaData(props) { console.log('getTaskflowMetaData', props); return { sessionId: props.simulation._id, }; } // ---------------------------------------------------------------------------- function getPayload(props) { console.log('getPayload', props); const sessionKey = props.simulation._id; return { sessionKey, // for pvw, we use this later for connecting, input: { file: { id: props.simulation.metadata.inputFolder.files.dataset, }, }, output: { folder: { id: props.simulation.metadata.outputFolder._id, }, }, }; } // ---------------------------------------------------------------------------- export default function openFoamStart(props) { return ( <JobSubmission {...props} actionList={actionList} clusterFilter={clusterFilter} getTaskflowMetaData={getTaskflowMetaData} getPayload={getPayload} /> ); }
app/components/Modal/Modal.js
klpdotorg/tada-frontend
import React from 'react'; import PropTypes from 'prop-types'; import ReactModal from 'react-modal'; import { modalStyle as customStyles } from '../../styles.js'; const Modal = (props) => { const { contentLabel, isOpen, onCloseModal, title, canSubmit, submitForm, cancelBtnLabel, submitBtnLabel, hideCancelBtn, children, } = props; return ( <ReactModal contentLabel={contentLabel} isOpen={isOpen} onRequestClose={onCloseModal} style={customStyles} > <div className="" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" onClick={onCloseModal} aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 className="modal-title" id="title"> {title} </h4> </div> <div className="modal-body" style={{ overflowY: 'auto', maxHeight: '28rem' }}> {children} </div> <div className="modal-footer"> {hideCancelBtn ? ( '' ) : ( <button type="button" className="btn btn-primary" onClick={onCloseModal}> {!cancelBtnLabel ? 'Discard' : cancelBtnLabel} </button> )} <button type="button" disabled={!canSubmit} className="btn btn-primary" onClick={submitForm} > {!submitBtnLabel ? 'Save' : submitBtnLabel} </button> </div> </div> </div> </ReactModal> ); }; Modal.propTypes = { title: PropTypes.string, contentLabel: PropTypes.string, cancelBtnLabel: PropTypes.string, submitBtnLabel: PropTypes.string, hideCancelBtn: PropTypes.bool, isOpen: PropTypes.bool, onCloseModal: PropTypes.func, canSubmit: PropTypes.bool, submitForm: PropTypes.func, children: PropTypes.element, }; export { Modal };
client/android/app/src/pages/CreateBillboard.js
blusclips/zonaster
import React, { Component } from 'react'; import { AppRegistry,StyleSheet,Text, View,AsyncStorage} from 'react-native'; import { Container, Content, Body, H2, Item, Input, Button, Picker} from 'native-base'; import general from '../styles/general'; import progressDialog from '../../../../src/progressDialog.js'; import {action, observable} from 'mobx'; import {observer} from 'mobx-react/native'; import {autobind} from 'core-decorators'; @observer @autobind export default class CreateBillboard extends Component { static navigationOptions = { header:null }; constructor(props) { super(props); this.store = this.props.screenProps.store; this.state = {userId:'', name:'', about:'', category:'', error:'', billName:true, billAbout:false, billCategory:false, selected1: 'key0'}; this.submitBillName = this.submitBillName.bind(this); this.submitBillAbout = this.submitBillAbout.bind(this); this.submitBillCategory = this.submitBillCategory.bind(this); changeState = (text) =>{ this.setState({error:text}); } changeStore = (data) => { this.store.billboardData(data); this.store.addBillboards(data); this.store.isBillEmpty = true; } navigateMe = (route) => { this.props.navigation.navigate(route); } } onValueChange (value: string) { this.setState({ selected1 : value }); } submitBillName = () =>{ if (this.state.name != "") { if (this.state.name.length > 5) { this.setState({billName:false}); this.setState({billAbout:true}); }else{ this.setState({error:"Billboard name must be more than four (4) characters long"}); } }else{ this.setState({error:"Enter name of the Billboard you want to create."}); } } submitBillAbout = () => { if (this.state.about != "") { if (this.state.about.length > 5 && this.state.about.length < 201) { this.setState({billAbout:false}); this.setState({billCategory:true}); }else{ this.setState({error:"Must be more than four (4) characters long and less than 200 characters long"}); } }else{ this.setState({error:"Tel us more about your Billboard"}); } } submitBillCategory = () => { let name = this.state.name; let about = this.state.about; let category = this.state.category; let userId = this.store.userId; let randomId = this.store.randomString(20); let location = "kasanga"; progressDialog.show("Creating Billboard, Please wait."); this.store.createBillboard(this.props.navigation, name, about, category, userId, randomId, location); } render() { const { navigate } = this.props.navigation; const { goBack} = this.props.navigation; return ( <Container> <Content> {this.state.billName ? <Body style={{marginTop:70, padding:20}}> <H2> Enter Billboard Name.</H2> <Text style={{textAlign:'center', marginTop:10, marginBottom:10}}> Your Bussiness Organisation Company or other name you prefer </Text> <Text style={{textAlign:'center', color:'red', fontWeight:'bold', marginBottom:20}}> {this.store.isError} </Text> <Item regular style={{marginBottom:35}}> <Input placeholder='Billboard name' onChangeText={(name) => this.setState({name})}/> </Item> <Button full rounded style={general.pad, general.primaryColorDark} onPress={this.submitBillName}> <Text style={general.clr}>Next</Text> </Button> </Body> : this.state.billAbout ? <Body style={{marginTop:70, padding:20, textAlign:'center'}}> <H2 style={{ marginBottom:40}}> What is your Billboard all about.</H2> <Item regular style={{marginBottom:35}}> <Input placeholder='About your Billboard' onChangeText={(about) => this.setState({about})}/> </Item> <Button full rounded style={general.pad, general.primaryColorDark} onPress={this.submitBillAbout}> <Text style={general.clr}> Next </Text> </Button> </Body> : <Body style={{marginTop:70, padding:20, textAlign:'center'}}> <H2 style={{ marginBottom:40, textAlign:'center'}}> Select Category for your Billboard</H2> <Picker style={{marginTop:40}} supportedOrientations={['portrait','landscape']} iosHeader="Select Category" mode="dropdown" selectedValue={this.state.selected1} onValueChange={this.onValueChange.bind(this)}> <Item label="Choose Category" value="select" /> <Item label="Sports" value="sports" /> <Item label="Music" value="music" /> <Item label="Movies" value="movies" /> <Item label="Other" value="other"/> </Picker> <Button full rounded style={general.pad, general.primaryColorDark} onPress={this.submitBillCategory}> <Text style={general.clr}> Create Billboard </Text> </Button> </Body> } </Content> </Container> ); } }
tests/lib/rules/vars-on-top.js
Cellule/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), EslintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var eslintTester = new EslintTester(eslint); eslintTester.addRuleTest("lib/rules/vars-on-top", { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), ecmaFeatures: { blockBindings: true } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
src/partials/footer.js
getinsomnia/insomnia.rest
import React from 'react'; import { menus, site } from '../config'; import Link from '../components/link'; import iconSrc from '../assets/icon.svg'; class Footer extends React.Component { render() { return ( <footer className="footer"> <div className="row"> <div className="col-4"> <div className="footer__branding"> <img src={iconSrc} alt="Insomnia REST Client logo" /> <span>&copy; {new Date().getUTCFullYear()}&nbsp;</span> <Link to={site.copyrightURL} target="_blank"> {site.copyright} </Link> </div> </div> <div className="col-4"> <p className="footer__menu"> {menus.footer && menus.footer.center.map(item => ( <Link key={item.key} to={item.url}> {item.name} </Link> ))} </p> </div> <div className="col-4"> <p className="footer__menu"> {menus.footer && menus.footer.right.map(item => ( <Link key={item.key} to={item.url}> {item.name} </Link> ))} </p> </div> </div> </footer> ); } } export default Footer;
client/components/router.js
olegccc/10cards
import React from 'react' import {Router, Route, IndexRoute, hashHistory} from 'react-router' import Home from './home' import AddCard from './addCard' import EditSet from './editSet' import EditCards from './editCards' import Layout from './layout' import ManageSets from './manageSets' const router = ( <Router history={hashHistory}> <Route component={Layout}> <IndexRoute components={{main: Home}}/> <Route path="/" components={{main: Home}}/> <Route path="/addCard" components={{main: AddCard}}/> <Route path="/manageSets" components={{main: ManageSets}}/> <Route path="/editSet/:id/addCard" components={{main: AddCard}}/> <Route path="/editSet/:id" components={{main: EditSet}}/> <Route path="/editCards/:setId" components={{main: EditCards}}/> <Route path="/editCard/:cardId" components={{main: AddCard}}/> </Route> </Router>); export default router;
src/svg-icons/action/assignment-turned-in.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentTurnedIn = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-2 14l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/> </SvgIcon> ); ActionAssignmentTurnedIn = pure(ActionAssignmentTurnedIn); ActionAssignmentTurnedIn.displayName = 'ActionAssignmentTurnedIn'; ActionAssignmentTurnedIn.muiName = 'SvgIcon'; export default ActionAssignmentTurnedIn;
ui/src/frontend/component/Repo.js
Virtustream-OSS/packrat
import React from 'react'; import CInP from './cinp'; import { Table, TableHead, TableRow, TableCell } from 'react-toolbox'; import { Link } from 'react-router-dom'; class Repo extends React.Component { state = { repo_list: [], repo: null }; componentDidMount() { this.update( this.props ); } componentWillReceiveProps( newProps ) { this.setState( { repo_list: [], repo: null } ); this.update( newProps ); } update( props ) { if( props.id !== undefined ) { props.getDetail( props.id ) .then( ( result ) => { var data = result.data; this.setState( { repo: data } ); } ); } else { props.getList() .then( ( result ) => { var repo_list = []; for ( var name in result.data ) { var repo = result.data[ name ]; name = CInP.extractIds( name )[0]; repo_list.push( { name: name, description: repo.description, created: repo.created, updated: repo.updated, } ); } this.setState( { repo_list: repo_list } ); } ); } } render() { if( this.props.id !== undefined ) { var repo = this.state.repo; return ( <div> <h3>Repo Detail</h3> { repo !== null && <div> <table> <thead/> <tbody> <tr><th>Name</th><td>{ repo.name }</td></tr> <tr><th>Description</th><td>{ repo.description }</td></tr> <tr><th>Fieldsystem Directory</th><td>{ repo.filesystem_dir }</td></tr> <tr><th>Distro Versions</th><td><ul>{ repo.distroversion_list.map( ( item, index ) => <li key={ index }><Link to={ '/distroversion/' + CInP.extractIds( item ) }>{ item }</Link></li> ) }</ul></td></tr> <tr><th>Manager Type</th><td>{ repo.manager_type }</td></tr> <tr><th>Releas Types</th><td><ul>{ repo.release_type_list.map( ( item, index ) => <li key={ index }><Link to={ '/releasetype/' + CInP.extractIds( item ) }>{ item }</Link></li> ) }</ul></td></tr> <tr><th>Show Only the Latest</th><td>{ repo.show_only_latest }</td></tr> <tr><th>Created</th><td>{ repo.created }</td></tr> <tr><th>Updated</th><td>{ repo.updated }</td></tr> </tbody> </table> </div> } </div> ); } return ( <Table selectable={ false } multiSelectable={ false }> <TableHead> <TableCell>Name</TableCell> <TableCell>Description</TableCell> <TableCell>Created</TableCell> <TableCell>Updated</TableCell> </TableHead> { this.state.repo_list.map( ( item ) => ( <TableRow key={ item.name } > <TableCell><Link to={ '/repo/' + item.name }>{ item.name }</Link></TableCell> <TableCell>{ item.description }</TableCell> <TableCell>{ item.created }</TableCell> <TableCell>{ item.updated }</TableCell> </TableRow> ) ) } </Table> ); } }; export default Repo
src/components/app/App.js
Miroku87/pogo-raids-organizer
import React, { Component } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom' import RaidMap from '../raid/RaidMap'; import Header from '../ui/Header'; import RaidInsert from '../raid/RaidInsert'; import RaidChat from '../raid/RaidChat'; import RaidInfo from '../raid/RaidInfo'; import Help from './Help'; import PositionWatcher from '../../utils/PositionWatcher'; import UserManager from '../../utils/UserManager'; import './App.css'; export default class App extends Component { constructor( props ) { super( props ); this.state = { map_center: null, info_popup_position: null } } positionNotFound = ( err ) => { console.log( err ); } positionUpdate = ( position ) => { let position_obj = { lat: position.coords.latitude, lng: position.coords.longitude }; this.setState( { map_center: position_obj } ); } userLogged = () => { } setupFacebookSDK = () => { window.fbAsyncInit = () => { window.FB.init( { appId: '324218624671234', cookie: true, xfbml: true, version: 'v2.8' } ); window.FB.AppEvents.logPageView(); UserManager.checkFacebookLogin( false, this.userLogged ); }; ( function ( d, s, id ) { var js, fjs = d.getElementsByTagName( s )[0]; if ( d.getElementById( id ) ) { return; } js = d.createElement( s ); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore( js, fjs ); }( document, 'script', 'facebook-jssdk' ) ); } setupPositionWatcher = () => { this.positionWatcher = new PositionWatcher(); this.positionWatcher.addListener( PositionWatcher.POSITION_UPDATE, this.positionUpdate ); this.positionWatcher.addListener( PositionWatcher.POSITION_NOT_FOUND, this.positionNotFound ); if ( this.state.map_center ) this.setState( { info_popup_position: this.state.map_center } ); } componentDidMount = () => { this.setupPositionWatcher(); this.setupFacebookSDK(); } componentWillUnmount = () => { this.positionWatcher.stopWatching(); }; render() { return ( <Router> <div className="app"> <Header title="PoGo Raid Organizer" search_placeholder="Livello o pok&eacute;mon" search_action="Filtra" /> <Route exact path="/" render={props => ( <RaidMap ref={( map ) => { this.map = map; }} mapCenter={this.state.map_center} {...props} /> )} /> <Route path="/raid_insert/:lat/:lng" component={RaidInsert} /> <Route path="/raid_chat/:id" component={RaidChat} /> <Route path="/raid_info/:id" component={RaidInfo} /> <Route path="/help" component={Help} /> </div> </Router> ); } }
src/pages/About/index.js
thisiskylierose/react-boilerplate
// @flow import React from 'react'; // import bootstrap from '../../../styles/bootstrap.less'; const About = (): React$Element<*> => ( <div> <h2>About page</h2> </div> ); export default About;
demo/src/components/App/App.js
moroshko/react-autowhatever
import styles from './App.less'; import React from 'react'; import ForkMeOnGitHub from 'ForkMeOnGitHub/ForkMeOnGitHub'; import Example0 from 'Example0/Example0'; import Example1 from 'Example1/Example1'; import Example2 from 'Example2/Example2'; import Example3 from 'Example3/Example3'; import Example4 from 'Example4/Example4'; import Example5 from 'Example5/Example5'; import Example6 from 'Example6/Example6'; import Example7 from 'Example7/Example7'; import Example8 from 'Example8/Example8'; import Example9 from 'Example9/Example9'; import Example10 from 'Example10/Example10'; import Example11 from 'Example11/Example11'; import Example12 from 'Example12/Example12'; export default function App() { return ( <div className={styles.container}> <div className={styles.headerContainer}> <h1 className={styles.header}> React Autowhatever </h1> <h2 className={styles.subHeader}> Accessible rendering layer for Autosuggest and Autocomplete components </h2> </div> <div className={styles.examplesContainer}> <div className={styles.exampleContainer}> <Example0 /> </div> <div className={styles.exampleContainer}> <Example1 /> </div> <div className={styles.exampleContainer}> <Example2 /> </div> <div className={styles.exampleContainer}> <Example3 /> </div> <div className={styles.exampleContainer}> <Example4 /> </div> <div className={styles.exampleContainer}> <Example5 /> </div> <div className={styles.exampleContainer}> <Example6 /> </div> <div className={styles.exampleContainer}> <Example7 /> </div> <div className={styles.exampleContainer}> <Example8 /> </div> <div className={styles.exampleContainer}> <Example9 /> </div> <div className={styles.exampleContainer}> <Example10 /> </div> <div className={styles.exampleContainer}> <Example11 /> </div> <div className={styles.exampleContainer}> <Example12 /> </div> </div> <ForkMeOnGitHub user="moroshko" repo="react-autowhatever" /> </div> ); }