path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
js/components/shared/LoadingIndicator.android.js
kort/kort-reloaded
import React from 'react'; import { ProgressBarAndroid, View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ overlayContainer: { flex: 1, justifyContent: 'center', position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, backgroundColor: 'rgba(255,255,255,0)', }, spinner: { width: 60, height: 60, alignSelf: 'center', }, }); const LoadingIndicator = () => ( <View style={styles.overlayContainer}> <ProgressBarAndroid style={styles.spinner} /> </View> ); module.exports = LoadingIndicator;
ignite/DevScreens/APITestingScreen.js
littletimo/beer-counter
import React from 'react' import { ScrollView, View, Text, TouchableOpacity, Image } from 'react-native' import { Metrics, Images } from './DevTheme' import FullButton from '../../App/Components/FullButton' // For API import API from '../../App/Services/Api' import FJSON from 'format-json' // Styles import styles from './Styles/APITestingScreenStyles' // API buttons here: const endpoints = [ { label: 'Github Root', endpoint: 'getRoot' }, { label: 'Github Rate Limit', endpoint: 'getRate' }, { label: 'Search User (gantman)', endpoint: 'getUser', args: ['gantman'] }, { label: 'Search User (skellock)', endpoint: 'getUser', args: ['skellock'] } ] export default class APITestingScreen extends React.Component { api = {} constructor (props) { super(props) this.state = { visibleHeight: Metrics.screenHeight } this.api = API.create() } showResult (response, title = 'Response') { this.refs.container.scrollTo({x: 0, y: 0, animated: true}) if (response.ok) { this.refs.result.setState({message: FJSON.plain(response.data), title: title}) } else { this.refs.result.setState({message: `${response.problem} - ${response.status}`, title: title}) } } tryEndpoint (apiEndpoint) { const { label, endpoint, args = [''] } = apiEndpoint this.api[endpoint].apply(this, args).then((result) => { this.showResult(result, label || `${endpoint}(${args.join(', ')})`) }) } renderButton (apiEndpoint) { const { label, endpoint, args = [''] } = apiEndpoint return ( <FullButton text={label || `${endpoint}(${args.join(', ')})`} onPress={this.tryEndpoint.bind(this, apiEndpoint)} styles={{marginTop: 10}} key={`${endpoint}-${args.join('-')}`} /> ) } renderButtons () { return endpoints.map((endpoint) => this.renderButton(endpoint)) } render () { return ( <View style={styles.mainContainer}> <Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' /> <TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{ position: 'absolute', paddingTop: 30, paddingHorizontal: 5, zIndex: 10 }}> <Image source={Images.backButton} /> </TouchableOpacity> <ScrollView style={styles.container} ref='container'> <View style={{alignItems: 'center', paddingTop: 60}}> <Image source={Images.api} style={styles.logo} /> <Text style={styles.titleText}>API</Text> </View> <View style={styles.section}> <Text style={styles.sectionText}> Testing API with Postman or APIary.io verifies the server works. The API Test screen is the next step; a simple in-app way to verify and debug your in-app API functions. </Text> <Text style={styles.sectionText}> Create new endpoints in Services/Api.js then add example uses to endpoints array in Containers/APITestingScreen.js </Text> </View> {this.renderButtons()} <APIResult ref='result' /> </ScrollView> </View> ) } } class APIResult extends React.Component { constructor (props) { super(props) this.state = { message: false, title: false } } onApiPress = () => { this.setState({message: false}) } renderView () { return ( <ScrollView style={{ top: 0, bottom: 0, left: 0, right: 0, position: 'absolute' }} overflow='hidden'> <TouchableOpacity style={{backgroundColor: 'white', padding: 20}} onPress={this.onApiPress} > <Text>{this.state.title} Response:</Text> <Text allowFontScaling={false} style={{fontFamily: 'CourierNewPS-BoldMT', fontSize: 10}}> {this.state.message} </Text> </TouchableOpacity> </ScrollView> ) } render () { let messageView = null if (this.state.message) { return this.renderView() } return messageView } }
src/js/components/MenuLink.js
gogrademe/WebApp
import React from 'react'; import { NavLink } from 'react-router-dom'; import { Menu } from 'semantic-ui-react' export default (props) => <Menu.Item as={NavLink} activeClassName='active' {...props} />;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
ChrisHIPPO/Mockstock
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
docs/app/Examples/elements/Label/Groups/LabelExampleGroupColored.js
vageeshb/Semantic-UI-React
import React from 'react' import { Icon, Label } from 'semantic-ui-react' const LabelExampleGroupSize = () => ( <Label.Group color='blue'> <Label as='a'> Fun <Icon name='close' /> </Label> <Label as='a'> Happy <Label.Detail>22</Label.Detail> </Label> <Label as='a'>Smart</Label> <Label as='a'>Insane</Label> <Label as='a'>Exciting</Label> </Label.Group> ) export default LabelExampleGroupSize
react-flux-mui/js/material-ui/src/svg-icons/hardware/keyboard-capslock.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardCapslock = (props) => ( <SvgIcon {...props}> <path d="M12 8.41L16.59 13 18 11.59l-6-6-6 6L7.41 13 12 8.41zM6 18h12v-2H6v2z"/> </SvgIcon> ); HardwareKeyboardCapslock = pure(HardwareKeyboardCapslock); HardwareKeyboardCapslock.displayName = 'HardwareKeyboardCapslock'; HardwareKeyboardCapslock.muiName = 'SvgIcon'; export default HardwareKeyboardCapslock;
frontend/src/components/shared/select-field/index.js
Kilte/cindy
import React from 'react'; import FocusLost from '../focus-lost'; import TextField from '../text-field'; import './index.css'; class SelectField extends React.Component { constructor(props) { super(props); this.state = {open: false}; this.hide = this.hide.bind(this); this.switch = this.switch.bind(this); } render() { return <div className="select-field"> <FocusLost onFocusLost={this.hide}> <div> <TextField hint={this.props.hint} onClick={this.switch} label={this.props.label} readOnly={true} value={this.props.items[this.props.value]} /> <div className="select-field-items" style={{display: this.state.open ? '' : 'none'}}> { Object.keys(this.props.items).map(value => <div className="select-field-item" key={value} onClick={this.selectItem(value)}> {this.props.items[value]} </div> ) } </div> </div> </FocusLost> </div>; } hide() { if (this.state.open) { this.setState({open: false}); } } switch() { this.setState({open: !this.state.open}); } selectItem(value) { return () => { this.props.onChange(value); this.setState({open: false}); }; } } SelectField.propTypes = { hint: React.PropTypes.string, items: React.PropTypes.object, label: React.PropTypes.string, onChange: React.PropTypes.func, value: React.PropTypes.string }; export default SelectField;
src/components/Sections/SectionNumber.js
demisto/sane-reports
import './SectionNumber.less'; import React from 'react'; import PropTypes from 'prop-types'; import values from 'lodash/values'; import classNames from 'classnames'; import { CHART_LAYOUT_TYPE, WIDGET_VALUES_FORMAT } from '../../constants/Constants'; import { capitalizeFirstLetter, formatNumberValue } from '../../utils/strings'; const TREND_NUMBER_LIMIT = 999; const SectionNumber = ({ data, layout, style, sign, signAlignment, title, titleStyle, valuesFormat = WIDGET_VALUES_FORMAT.abbreviated, subTitle, numberStyle = {} }) => { const isTrend = !!data.prevSum || data.prevSum === 0; let percentage = 0; const curr = data.currSum || 0; if (isTrend) { const prev = data.prevSum || 0; const divider = prev === 0 ? 1 : prev; percentage = parseInt(((curr - prev) / divider) * 100, 10); } const caretClass = classNames('trend-icon caret icon', { up: percentage > 0, red: percentage > 0 && style.backgroundColor, down: percentage < 0, green: percentage < 0 && style.backgroundColor }); const trendIcon = percentage === 0 ? (<span className="trend-icon trend-equal">=</span>) : (<i className={caretClass} />); let shortPercentage = Math.abs(percentage) + ''; if (isTrend && percentage > TREND_NUMBER_LIMIT) { shortPercentage = `>${TREND_NUMBER_LIMIT}`; } const color = style && style.backgroundColor ? '#FFF' : undefined; const titleColor = (titleStyle && titleStyle.color) ? titleStyle.color : color; const subTitleClass = classNames('demisto-number-sub-title', { 'color-warning': !color }); let trendContainer = ''; if (isTrend) { const boxClass = classNames('trend-box', { red: !style.backgroundColor && percentage > 0, green: !style.backgroundColor && percentage < 0, grey: !style.backgroundColor && percentage === 0 }); trendContainer = ( <div className="trend-container"> <div className={boxClass}> {trendIcon} {shortPercentage}% </div> </div> ); } const signElement = <span className="sign">{sign}</span>; return ( <div className="section-number" style={style}> <div className="number-container"> <div className="trend-num-text" style={{ ...numberStyle, color }} > {signAlignment === 'left' && signElement} {formatNumberValue(curr, valuesFormat === WIDGET_VALUES_FORMAT.percentage ? WIDGET_VALUES_FORMAT.regular : valuesFormat)} {signAlignment === 'right' && signElement} </div> {layout === CHART_LAYOUT_TYPE.horizontal && isTrend && trendContainer } <div className="trend-message" style={{ ...titleStyle, color: titleColor }}> {capitalizeFirstLetter(title)} {subTitle && ( <div className={subTitleClass} style={{ color: color || '#ff9000' }} title={subTitle}> {subTitle} </div> )} </div> {layout === CHART_LAYOUT_TYPE.vertical && isTrend && trendContainer } </div> </div> ); }; SectionNumber.propTypes = { data: PropTypes.object, style: PropTypes.object, title: PropTypes.string, titleStyle: PropTypes.object, numberStyle: PropTypes.object, layout: PropTypes.oneOf(values(CHART_LAYOUT_TYPE)), sign: PropTypes.string, signAlignment: PropTypes.string, valuesFormat: PropTypes.oneOf(values(WIDGET_VALUES_FORMAT)), subTitle: PropTypes.string }; export default SectionNumber;
components/form/Checkbox.js
resource-watch/resource-watch
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Icon from 'components/ui/icon'; import FormElement from './FormElement'; export default class Checkbox extends FormElement { /** * UI EVENTS * - triggerChange */ triggerChange(evt) { const { value } = this.props.properties; this.props.onChange && this.props.onChange({ value, checked: evt.currentTarget.checked, }); } render() { const { name, value, title, className, } = this.props.properties; const customClassName = classnames({ [className]: !!className, }); return ( <div className={`c-checkbox ${customClassName}`}> <input {...this.props.properties} type="checkbox" id={`checkbox-${name}-${value}`} onChange={this.triggerChange} /> <label htmlFor={`checkbox-${name}-${value}`}> <span className="checkbox-icon"> <Icon name="icon-checkbox" /> </span> <span className="item-title">{title}</span> </label> </div> ); } } Checkbox.propTypes = { properties: PropTypes.object, onChange: PropTypes.func, };
client/src/modules/registration/registration.view.js
euqen/spreadsheet-core
'use strict'; import React from 'react'; import {Link} from 'react-router'; import ErrorCollector from './../../components/error-collector'; import dispatcher from './../../infrastructure/dispatcher'; import bind from './../../infrastructure/store-connector'; import store from './registration.store'; import counterpart from 'counterpart'; import Translate from 'react-translate-component'; import LocalizationService from './../../infrastructure/localization-service'; counterpart.registerTranslations('en', { registerNewPerson: "Register new person", email: "Email", firstName: "First Name", middleName: "Middle Name", lastName: "Last Name", roles: "Roles", roleTypes: { manager: "Manager", teacher: "Teacher", student: "Student" }, studentsGroup: "Student's group", create: "Create" }); counterpart.registerTranslations('ru', { registerNewPerson: "Зарегистрировать нового человека", email: "Email", firstName: "Имя", middleName: "Отчество", lastName: "Фамилия", roles: "Роль", roleTypes: { manager: "Админ", teacher: "Преподаватель", student: "Студент" }, studentsGroup: "Группа студента", create: "Создать" }); const additionalConstants = { en: { enterEmail: "Enter email", firstName: "First Name", middleName: "Middle Name", lastName: "Last Name" }, ru: { enterEmail: "Введите email", firstName: "Имя", middleName: "Отчество", lastName: "Фамилия", } }; function getState(props) { return { user: props.user, groups: props.groups } } @bind(store, getState) export default class Registration extends React.Component { constructor(props) { super(props); this.state = { user: {}, groups: [] }; this.onValueChanged = this.onValueChanged.bind(this); this.create = this.create.bind(this); this.renderGroups = this.renderGroups.bind(this); this.state.localizationService = new LocalizationService(additionalConstants); } componentDidMount() { dispatcher.dispatch({action: 'groups.retrieve'}); } componentWillReceiveProps(props) { if (props.groups) { this.setState({groups: props.groups}); } } onValueChanged(event) { this.setState({[event.target.name]: event.target.value}); } renderGroups() { if (this.state.groups) { return this.state.groups.map(g => <option key={g._id} value={g._id}>{g.groupNumber}</option>); } } create() { const data = { email: this.state.email, firstName: this.state.firstName, middleName: this.state.middleName, lastName: this.state.lastName, role: this.state.role, group: this.state.group }; dispatcher.dispatch({action: 'user.create', user: data}) } render() { return ( <div> <ErrorCollector /> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title"><Translate content="registerNewPerson" /></h3> </div> <div className="panel-body"> <div className="row"> <div className="col-md-12 col-sm-12 col-xs-12"> <form role="form"> <div className="form-group"> <label htmlFor="email"><Translate content="email" /></label> <input type="email" className="form-control" id="email" placeholder={this.state.localizationService.translate("enterEmail")} name="email" onChange={this.onValueChanged} /> </div> <div className="form-group"> <label htmlFor="firstname"> <Translate content="firstName" /></label> <input type="text" className="form-control" id="firstname" placeholder={this.state.localizationService.translate("firstName")} name="firstName" onChange={this.onValueChanged} /> </div> <div className="form-group"> <label htmlFor="middlename"> <Translate content="middleName" /></label> <input type="text" className="form-control" id="middlename" placeholder={this.state.localizationService.translate("middleName")} name="middleName" onChange={this.onValueChanged} /> </div> <div className="form-group"> <label htmlFor="lastname"> <Translate content="lastName" /> </label> <input type="text" className="form-control" id="lastname" placeholder={this.state.localizationService.translate("lastName")} name="lastName" onChange={this.onValueChanged} /> </div> <div className="form-group"> <label><Translate content="roles" /></label> <div className="radio"> <label className="cr-styled" forHtml="manager"> <input type="radio" id="manager" name="permissions" value="manager" name="role" onChange={this.onValueChanged} /> <i className="fa"></i> <span><Translate content="roleTypes.manager" /></span> </label> </div> <div className="radio"> <label className="cr-styled" forHtml="teacher"> <input type="radio" id="teacher" name="permissions" value="teacher" name="role" onChange={this.onValueChanged} /> <i className="fa"></i> <span><Translate content="roleTypes.teacher" /></span> </label> </div> <div className="radio"> <label className="cr-styled" forHtml="student"> <input type="radio" id="student" name="permissions" value="student" name="role" onChange={this.onValueChanged} /> <i className="fa"></i> <span><Translate content="roleTypes.student" /></span> </label> </div> </div> {this.state.role === 'student' ? <div className="form-group"> <label htmlFor="role"> <Translate content="studentsGroup" /> </label> <select className="form-control" onChange={this.onValueChanged.bind(this)} name="group"> <option value="">Select group</option> {this.renderGroups()} </select> </div> : null } <button onClick={this.create} type="button" className="btn btn-success pull-right"><Translate content="create" /></button> </form> </div> </div> </div> </div> </div> ); } }
app/weather.js
wvicioso/dapr
import React, { Component } from 'react'; import { Navigator, StyleSheet, Text, TextInput, ScrollView, TouchableOpacity, View, Image, ListView } from 'react-native'; const Carousel = require('react-native-carousel'); const SideMenu = require('react-native-side-menu'); export default class Weather extends Component { constructor() { super(); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([]), temp: '', cond: '', city: '', wind: '', icon: '' } } navigate(routeName) { this.props.navigator.push({ name : routeName }) } componentDidMount() { fetch("http://ap.wunderground.com/api/ae341c3c3cc0ff78/geolookup/conditions/q/NY/New_York_City.json", { method: 'get' }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); if (responseJson !== null) { this.setState({ temp: responseJson.current_observation.temp_f, cond: responseJson.current_observation.weather, wind: responseJson.current_observation.wind_mph, city: responseJson.location.city, icon: responseJson.current_observation.icon_url, }) console.log(this.state.icon) } }) .catch((error) => { debugger throw new Error(error) }) } render() { return ( <View style={{}}> <Text> hello </Text> </View> ); } } const styles = StyleSheet.create({ container: { width: 100, backgroundColor: 'transparent', }, });
src/svg-icons/action/list.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionList = (props) => ( <SvgIcon {...props}> <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/> </SvgIcon> ); ActionList = pure(ActionList); ActionList.displayName = 'ActionList'; ActionList.muiName = 'SvgIcon'; export default ActionList;
imports/ui/pages/Miscellaneous/Login/Login.js
haraneesh/mydev
import React from 'react'; import { Col, FormGroup, Button, Panel, } from 'react-bootstrap'; import { Link } from 'react-router-dom'; import { Meteor } from 'meteor/meteor'; import { toast } from 'react-toastify'; // import OAuthLoginButtons from '../../../components/OAuthLoginButtons/OAuthLoginButtons'; import AccountPageFooter from '../../../components/AccountPageFooter/AccountPageFooter'; import { getLoggedInUserDisplayUserName } from '../../../../modules/helpers'; import { formValid, formValChange } from '../../../../modules/validate'; const showPasswordButtonPositions = { position: 'relative', top: '-41px', padding: '10px', right: '6px', float: 'right', fontSize: '75%', }; const defaultState = { isError: { whMobilePhone: '', password: '', }, showPassword: false, }; class Login extends React.Component { constructor(props) { super(props); this.state = { ...defaultState }; this.handleSubmit = this.handleSubmit.bind(this); this.switchPasswordBox = this.switchPasswordBox.bind(this); this.validateForm = this.validateForm.bind(this); this.onValueChange = this.onValueChange.bind(this); } onValueChange(e) { e.preventDefault(); const { isError } = this.state; const newState = formValChange(e, { ...isError }); this.setState(newState); } handleSubmit() { const username = { username: this.whMobilePhone.value.trim() }; const password = document.getElementsByName('password')[0].value.trim(); Meteor.loginWithPassword(username, password, (error) => { if (error) { toast.warn(error.reason); } else { toast.success(`Welcome ${getLoggedInUserDisplayUserName()}`); } }); } validateForm(e) { e.preventDefault(); const { isError } = this.state; if (formValid({ isError })) { this.handleSubmit(); } else { this.setState({ isError }); } } switchPasswordBox() { this.setState({ showPassword: !this.state.showPassword }); } render() { const { isError } = this.state; return ( <div className="Login Absolute-Center is-Responsive offset-sm-1"> <Col xs={12} sm={6} md={5} lg={4}> <h2 className="page-header">Log In</h2> <form onSubmit={this.validateForm}> <FormGroup validationState={isError.whMobilePhone.length > 0 ? 'error' : null}> <label className="control-label">Mobile Number</label> <input type="text" name="whMobilePhone" ref={(whMobilePhone) => (this.whMobilePhone = whMobilePhone)} className="form-control" placeholder="10 digit number example, 8787989897" onBlur={this.onValueChange} /> {isError.whMobilePhone.length > 0 && ( <span className="control-label">{isError.whMobilePhone}</span> )} </FormGroup> <FormGroup validationState={isError.password.length > 0 ? 'error' : null} style={{ position: 'relative' }}> <label className="clearfix control-label"> <span className="pull-left">Password</span> <Link className="pull-right" to="/recover-password">Forgot password?</Link> </label> <input type={(this.state.showPassword ? 'text' : 'password')} name="password" className="form-control" placeholder="Password" onBlur={this.onValueChange} /> <Button className="btn-xs btn-info" onClick={this.switchPasswordBox} style={showPasswordButtonPositions} > {this.state.showPassword ? 'Hide' : 'Show'} </Button> {isError.password.length > 0 && ( <span className="control-label">{isError.password}</span> )} </FormGroup> <Button type="submit" bsStyle="primary" className="loginBtn">Log In</Button> <AccountPageFooter> <div className="panel text-center" style={{ marginBottom: '0px', padding: '6px' }}> <span> {'Not a member yet? '} <a href="/signup" className="login-signup">Join</a> </span> </div> </AccountPageFooter> </form> {/* } <Row> <p>- Or - </p> </Row> <Row> <Col xs={12}> <OAuthLoginButtons services={['facebook' , 'github', 'google']} /> </Col> </Row> */} </Col> </div> ); } } export default Login;
src/server.js
Padelas649/moralgram
// src/server.js import path from 'path'; import { Server } from 'http'; import Express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import routes from './routes'; import NotFoundPage from './components/NotFoundPage'; const app = new Express(); const server = new Server(app); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(Express.static(path.join(__dirname, '../public'))); // universal routing and rendering app.get('*', (req, res) => { match( { routes, location: req.url }, (err, redirectLocation, renderProps) => { // in case of error display the error message if (err) { return res.status(500).send(err.message); } // in case of redirect propagate the redirect to the browser if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } // generate the React markup for the current route let markup; if (renderProps) { //console.log(renderProps); // if the current route matched we have renderProps markup = renderToString(<RouterContext {...renderProps}/>); } else { // otherwise we can render a 404 page markup = renderToString(<NotFoundPage/>); res.status(404); } // render the index template with the embedded React markup return res.render('index', { markup }); } ); }); app.listen(649, () => { console.log('Dilemmas started on port 649!'); })
src/components/PageHeader.js
ChicagoJS/chicagojs.org
import React from 'react' import './PageHeader.css' import PropType from 'prop-types' import { isValidUrl } from '../utils' const PageHeader = ({ background, title, titleColor, gradient }) => { const generateBackground = background => ({ background: isValidUrl(background) ? `linear-gradient(to right bottom, ${gradient[0]}, ${gradient[1]}), url(${background})` : background }) return ( <div className="jumbotron jumbotron-fluid PageHeaderBackground" style={generateBackground(background)}> <div className="container"> <div className="text-center"> <h1 className="PageHeader" style={{ color: titleColor }}> {title} </h1> </div> </div> </div> ) } PageHeader.propTypes = { background: PropType.string, titleColor: PropType.string, title: PropType.string.isRequired, gradient: PropType.array } PageHeader.defaultProps = { background: '#ffffff', titleColor: '#000000', title: 'Default Title', gradient: ['rgba(0,0,0,.4)', 'rgba(0,0,0,.4)'] } export default PageHeader
src/components/serpListItem.js
joeterrell/SerpMonsterReactApp
import React, { Component } from 'react'; class SerpListItem extends Component { constructor(props) { super(props); }; render() { return ( <li className="list-group-item" data-active={this.props.active} onClick={() => { this.props.onResultSelect(this.props.resultKey) this.props.handleSerpSelected(this.props.resultKey) } }> <div className="video-list media"> <div className="media-body"> <div>SERP: "{this.props.serpResult}"</div> </div> </div> </li> ); } }; export default SerpListItem;
share/components/LogIn/index.js
caojs/password-manager-server
import React from 'react'; import { connect } from 'react-redux'; import { createAction } from 'redux-actions'; import { reduxForm } from 'redux-form/immutable' import Immutable from 'immutable'; import LogIn from './LogIn'; import redirectTo from '../redirectTo'; import { post } from '../../api'; @connect(state => { const user = state.get('user') || Immutable.Map(); return { userData: user.get('data'), errors: user.get('errors') }; }) @redirectTo('/', ({ userData }) => userData && userData.size) @reduxForm({ form: 'login', onSubmit: (form, dispatch) => post('/login', form.toJS()).then(dispatch) }) class LogInContainer extends LogIn {} LogInContainer.onEnter = (nextState, replace, { getState }) => { const user = getState().getIn(['user', 'data']); if (user && user.size) { replace('/'); } }; export default LogInContainer;
src/svg-icons/action/bookmark.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBookmark = (props) => ( <SvgIcon {...props}> <path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionBookmark = pure(ActionBookmark); ActionBookmark.displayName = 'ActionBookmark'; ActionBookmark.muiName = 'SvgIcon'; export default ActionBookmark;
examples/forms-material-ui/src/components/_common/CodeExample/CodeBlockTitle.js
lore/lore-forms
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from 'material-ui/IconButton'; import CodeIcon from 'material-ui/svg-icons/action/code'; import {Toolbar, ToolbarGroup, ToolbarTitle} from 'material-ui/Toolbar'; const CodeBlockTitle = (props) => ( <Toolbar> <ToolbarGroup> <ToolbarTitle text={props.title || 'Example'} /> </ToolbarGroup> <ToolbarGroup> <IconButton touch={true} tooltip={props.tooltip}> <CodeIcon /> </IconButton> </ToolbarGroup> </Toolbar> ); CodeBlockTitle.propTypes = { title: PropTypes.string, tooltip: PropTypes.string, }; export default CodeBlockTitle;
src/esm/components/graphics/icons/rocket-circle-icon/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "bgColor", "circleColor", "circleWidth", "circleWidthMobile", "rocketWidth", "rocketWidthMobile", "rocketHeight", "rocketHeightMobile", "rocketColor", "rocketTitle", "className"]; import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { RocketIcon } from '../rocket-icon'; import { pxToRem } from '../../../../helpers/utils/typography'; import COLORS from '../../../../constants/colors-config'; import { ScreenConfig } from '../../../../constants/screen-config'; import deprecated from 'prop-types-extra/lib/deprecated'; import classNames from 'classnames'; var StyledRocketCircle = styled.div.withConfig({ displayName: "rocket-circle-icon__StyledRocketCircle", componentId: "sc-hjcjwz-0" })(["display:flex;justify-content:center;align-items:center;width:", ";height:", ";border-radius:var(border-radius-rounded);background-color:", ";@media (min-width:", "){width:", ";height:", ";}.k-RocketCircleIcon__rocketIcon{padding-right:", ";padding-top:", ";width:", ";height:", ";@media (min-width:", "){width:", ";height:", ";}}"], function (_ref) { var circleWidthMobile = _ref.circleWidthMobile; return pxToRem(circleWidthMobile); }, function (_ref2) { var circleWidthMobile = _ref2.circleWidthMobile; return pxToRem(circleWidthMobile); }, function (_ref3) { var bgColor = _ref3.bgColor; return bgColor; }, pxToRem(ScreenConfig.S.min), function (_ref4) { var circleWidth = _ref4.circleWidth; return pxToRem(circleWidth); }, function (_ref5) { var circleWidth = _ref5.circleWidth; return pxToRem(circleWidth); }, pxToRem(2), pxToRem(1), function (_ref6) { var rocketWidthMobile = _ref6.rocketWidthMobile; return pxToRem(rocketWidthMobile); }, function (_ref7) { var rocketHeightMobile = _ref7.rocketHeightMobile; return pxToRem(rocketHeightMobile); }, pxToRem(ScreenConfig.S.min), function (_ref8) { var rocketWidth = _ref8.rocketWidth; return pxToRem(rocketWidth); }, function (_ref9) { var rocketHeight = _ref9.rocketHeight; return pxToRem(rocketHeight); }); export var RocketCircleIcon = function RocketCircleIcon(_ref10) { var color = _ref10.color, bgColor = _ref10.bgColor, circleColor = _ref10.circleColor, circleWidth = _ref10.circleWidth, circleWidthMobile = _ref10.circleWidthMobile, rocketWidth = _ref10.rocketWidth, rocketWidthMobile = _ref10.rocketWidthMobile, rocketHeight = _ref10.rocketHeight, rocketHeightMobile = _ref10.rocketHeightMobile, rocketColor = _ref10.rocketColor, rocketTitle = _ref10.rocketTitle, className = _ref10.className, others = _objectWithoutPropertiesLoose(_ref10, _excluded); return /*#__PURE__*/React.createElement(StyledRocketCircle, _extends({ circleWidth: circleWidth, circleWidthMobile: circleWidthMobile, bgColor: circleColor || bgColor, rocketWidth: rocketWidth, rocketHeight: rocketHeight, rocketHeightMobile: rocketHeightMobile, rocketWidthMobile: rocketWidthMobile, className: classNames('k-ColorSvg', className) }, others), /*#__PURE__*/React.createElement(RocketIcon, { color: color, title: rocketTitle, className: "k-RocketCircleIcon__rocketIcon" })); }; RocketCircleIcon.defaultProps = { bgColor: COLORS.valid, circleWidth: 24, circleWidthMobile: 20, color: COLORS.background1, rocketHeight: 15, rocketHeightMobile: 12, rocketTitle: '', rocketWidth: 12, rocketWidthMobile: 10 }; RocketCircleIcon.propTypes = { circlewidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), circlewidthMobile: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), circleColor: deprecated(PropTypes.string, '`circleColor` is deprecated. Please use `bgColor` instead.'), bgColor: PropTypes.string, rocketWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), rocketHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), rocketWidthMobile: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), rocketHeightMobile: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), rocketTitle: PropTypes.string, rocketColor: deprecated(PropTypes.string, '`rocketColor` is deprecated. Please use `color` instead.'), color: PropTypes.string };
public/js/cat_source/es6/components/analyze/JobAnalyze.js
matecat/MateCat
import React from 'react' import _ from 'lodash' import JobAnalyzeHeader from './JobAnalyzeHeader' import JobTableHeader from './JobTableHeader' import ChunkAnalyze from './ChunkAnalyze' import AnalyzeConstants from '../../constants/AnalyzeConstants' import AnalyzeStore from '../../stores/AnalyzeStore' class JobAnalyze extends React.Component { constructor(props) { super(props) this.showDetails = this.showDetails.bind(this) } getChunks() { let self = this if (this.props.chunks) { return _.map(this.props.jobInfo.chunks, function (item, index) { let files = self.props.chunks.get(item.jpassword) index++ let job = self.props.project.get('jobs').find(function (jobElem) { return jobElem.get('password') === item.jpassword }) return ( <ChunkAnalyze key={item.jpassword} files={files} job={job} project={self.props.project} total={self.props.total.get(item.jpassword)} index={index} chunkInfo={item} chunksSize={_.size(self.props.jobInfo.chunks)} /> ) }) } return '' } showDetails(idJob) { if (idJob == this.props.idJob) { this.scrollElement() } } scrollElement() { let itemComponent = this.container let self = this if (itemComponent) { this.container.classList.add('show-details') $('html, body').animate( { scrollTop: $(itemComponent).offset().top, }, 500, ) // ReactDOM.findDOMNode(itemComponent).scrollIntoView({block: 'end'}); setTimeout(function () { self.container.classList.remove('show-details') }, 1000) } else { setTimeout(function () { self.scrollElement() }, 500) } } componentDidMount() { AnalyzeStore.addListener(AnalyzeConstants.SHOW_DETAILS, this.showDetails) } componentWillUnmount() { AnalyzeStore.removeListener(AnalyzeConstants.SHOW_DETAILS, this.showDetails) } shouldComponentUpdate() { return true } render() { return ( <div className="job ui grid"> <div className="job-body sixteen wide column"> <div className="ui grid chunks"> <div className="chunk-container sixteen wide column"> <div className="ui grid analysis" ref={(container) => (this.container = container)} > <JobAnalyzeHeader totals={this.props.total} project={this.props.project} jobInfo={this.props.jobInfo} status={this.props.status} /> <JobTableHeader rates={this.props.jobInfo.rates} /> {this.getChunks()} </div> </div> </div> </div> </div> ) } } export default JobAnalyze
src/containers/PlaceListPage.js
nickeblewis/walkapp
/** * Component that lists all Posts */ import React from 'react' import { Link } from 'react-router' import Place from '../components/Place' import { graphql } from 'react-apollo' import gql from 'graphql-tag' import { Map, Marker, Popup, TileLayer } from 'react-leaflet' class PlaceListPage extends React.Component { constructor() { super(); this.state = { lat: 51.27985, lng: -0.75159, zoom: 15, }; } static propTypes = { data: React.PropTypes.object, } render () { const position = [this.state.lat, this.state.lng]; if (this.props.data.loading) { return (<div>Loading</div>) } return ( <main> <Map center={position} zoom={this.state.zoom} scrollWheelZoom={false}> <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> <Marker position={position}> <Popup> <span>A pretty CSS3 popup.<br/>Easily customizable.</span> </Popup> </Marker> </Map> <section className='cf w-100 pa2-ns'> <Link to='/places/create' className='fixed bg-white top-0 right-0 pa4 ttu dim black no-underline'> + New Place </Link> {this.props.data.allPlaces.map((place) => <Place key={place.id} place={place} refresh={() => this.props.data.refetch()} /> )} </section> </main> ) } } const FeedQuery = gql`query allPlaces { allPlaces(filter: {published:true}, orderBy: createdAt_DESC) { id banner title slug summary } }` const PlaceListPageWithData = graphql(FeedQuery)(PlaceListPage) export default PlaceListPageWithData
src/svg-icons/editor/merge-type.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMergeType = (props) => ( <SvgIcon {...props}> <path d="M17 20.41L18.41 19 15 15.59 13.59 17 17 20.41zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5 7.5 8z"/> </SvgIcon> ); EditorMergeType = pure(EditorMergeType); EditorMergeType.displayName = 'EditorMergeType'; export default EditorMergeType;
src/webapp/config/routes.js
nus-mtp/cubist
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { AppContainer, AdminContainer, AdminModelsContainer, AdminUsersContainer, AdminLoginContainer, AuthorisationContainer, HomeContainer, LoginContainer, RegisterContainer, ResetPasswordContainer, ModelContainer, ModelEditContainer, UploadContainer, RootContainer, ErrorContainer, BrowseContainer, ProfileContainer } from 'webapp/components'; export default ( <Route component={ RootContainer }> <Route path="/" component={ AppContainer }> <IndexRoute component={ HomeContainer } /> <Route path="model/:modelId" component={ ModelContainer } /> <Route path="browse" component={ BrowseContainer } /> <Route component={ AuthorisationContainer }> <Route path="upload" component={ UploadContainer } /> <Route path="model/:modelId/edit" component={ ModelEditContainer } /> </Route> <Route path="u/:username" component={ ProfileContainer } /> <Route path="admin" component={ AdminContainer }> <IndexRoute component={ AdminModelsContainer } /> <Route path="user" component={ AdminUsersContainer } /> </Route> </Route> <Route path="/adminLogin" component={ AdminLoginContainer } /> <Route path="/login" component={ LoginContainer } /> <Route path="/register" component={ RegisterContainer } /> <Route path="/resetPassword" component={ ResetPasswordContainer } /> <Route path="*" component={ ErrorContainer } /> </Route> );
app/views/Template/Login/Login.js
RcKeller/STF-Refresh
import React from 'react' import PropTypes from 'prop-types' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { endSession } from '../../../services/authentication' import { environment } from '../../../services/' const { ENV } = environment /* LOGIN COMPONENT A branding-compliant component used to log in */ import styles from './Login.css' @connect( state => ({ user: state.user }), dispatch => ({ signOut: bindActionCreators(endSession, dispatch) }) ) class Login extends React.Component { static propTypes = { user: PropTypes.object, signOut: PropTypes.func } render ({ user, signOut } = this.props) { return ( <div className={styles['login']}> {!user.authenticated ? <a href={ENV === 'production' ? '/login' : '/auth/google'} > <button className={styles['button']} > <strong>{ENV === 'production' ? 'UW NetID' : 'UW MOCK'}</strong> <small>WEBLOGIN</small> </button> </a> : <button className={styles['button']} onClick={() => signOut()} > <strong>{user.netID}</strong> <small>Signed In</small> </button> } </div> ) } } export default Login
dispatch/static/manager/src/js/components/inputs/selects/PollSelectInput.js
ubyssey/dispatch
import React from 'react' import { connect } from 'react-redux' import ItemSelectInput from './ItemSelectInput' import pollsActions from '../../../actions/PollsActions' class PollSelectInputComponent extends React.Component { listPolls(query) { let queryObj = {} if (query) { queryObj['q'] = query } this.props.listPolls(this.props.token, queryObj) } render() { const label = this.props.many ? 'polls' : 'poll' return ( <ItemSelectInput many={false} value={this.props.value} results={this.props.polls.ids} entities={this.props.entities.polls} onChange={(value) => this.props.onChange(value)} fetchResults={(query) => this.listPolls(query)} attribute='name' editMessage={this.props.value ? `Edit ${label}` : `Add ${label}`} /> ) } } const mapStateToProps = (state) => { return { polls: state.app.polls.list, entities: { polls: state.app.entities.polls }, token: state.app.auth.token } } const mapDispatchToProps = (dispatch) => { return { listPolls: (token, query) => { dispatch(pollsActions.list(token, query)) } } } const PollSelectInput = connect( mapStateToProps, mapDispatchToProps )(PollSelectInputComponent) export default PollSelectInput
Examples/Example.ChromiumFx.Mobx.UI/View/mainview/src/index.js
David-Desmaisons/MVVM.CEF.Glue
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { ready } from './mobxManager'; import 'bootstrap/dist/css/bootstrap.css'; ready.then(res => { ReactDOM.render(<App viewModel={res.vm.ViewModel}/>, document.getElementById('root'), res.ready); })
src/library/Table/TableSelectableCell.js
mineral-ui/mineral-ui
/* @flow */ import React, { Component } from 'react'; import TableCell from './TableCell'; import TableHeaderCell from './TableHeaderCell'; import TableContext from './TableContext'; import { PaddedCheckbox } from './styled'; import type { TableSelectableCellProps } from './types'; export default class TableSelectableCell extends Component<TableSelectableCellProps> { static displayName = 'TableSelectableCell'; shouldComponentUpdate(nextProps: TableSelectableCellProps) { return ( this.props.checked !== nextProps.checked || this.props.indeterminate !== nextProps.indeterminate ); } render() { return ( <TableContext.Consumer> {({ density }) => { const { checked, disabled, indeterminate, isHeader, label, onChange, ...restProps } = this.props; const Root = isHeader ? TableHeaderCell : TableCell; const rootProps = { noPadding: true, width: isHeader ? 1 : undefined, ...restProps }; const checkboxProps = { checked, disabled, density, hideLabel: true, indeterminate, isHeader, label, onChange }; return ( <Root {...rootProps}> <PaddedCheckbox {...checkboxProps} /> </Root> ); }} </TableContext.Consumer> ); } }
client/framework-webclient/src/routes/Knowledge/subviews/StandardList/components/StandardEditView.js
DimitriZhao/sinosteel
import React from 'react'; import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, DatePicker, InputNumber, Card } from 'antd'; const FormItem = Form.Item; const Option = Select.Option; import EditView from 'common/basic/components/EditView'; import moment from 'moment'; import FormUpload from 'components/FormUpload/FormUpload.js'; import {editStandardService, deleteStandardResourceService} from 'services'; import {addKey} from 'utils/ArrayUtil'; import SubItemContainer from 'common/basic/containers/SubItemContainer' export default class StandardEditView extends EditView { constructor(props) { super(props); this.editPath = editStandardService //负责处理新增命令的url } handleInitValues = (initValues) => { //issueDate if(initValues.issueDate) { initValues.issueDate = moment(initValues.issueDate, 'YYYY-MM-DD'); } } handleValues = (values) => { //issueDate let date = values['issueDate']; if(date) { values['issueDate'] = date.format('YYYY-MM-DD'); } //files this.files = values['resources'] || true; values['resources'] = null; } render() { const formItems = []; const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 }, }; const width = '100%'; formItems.push( <Card key='0' title='标准基本信息' style={{marginBottom: 20}}> <Row key='0'> <Col span={12}> <FormItem {...formItemLayout} label="标准名称" > {getFieldDecorator('name', { rules: [{ required: true, message: '请填写标准名称' }], })( <Input style={{width: width}}/> )} </FormItem> </Col> <Col span={12}> <FormItem {...formItemLayout} label="标准号" > {getFieldDecorator('code', { rules: [{ required: true, message: '请填写标准号' }], })( <Input style={{width: width}}/> )} </FormItem> </Col> </Row> <Row key='1'> <Col span={12}> <FormItem {...formItemLayout} label='状态'> {getFieldDecorator('status', { })( <Select style={{width: width}}> <Option value="1">在执行</Option> <Option value="0">废止</Option> </Select> )} </FormItem> </Col> <Col span={12}> <FormItem {...formItemLayout} label='类型'> {getFieldDecorator('type', { })( <Select style={{width: width}}> <Option value="0">强制</Option> <Option value="1">行业</Option> <Option value="2">推荐</Option> </Select> )} </FormItem> </Col> </Row> <Row key='2'> <Col span={12}> <FormItem {...formItemLayout} label="颁布日期" > {getFieldDecorator('issueDate', { rules: [{ required: true, message: '请选择颁布日期' }], })( <DatePicker style={{width: width}}/> )} </FormItem> </Col> </Row> <Row key='3'> <FormItem { ... { labelCol: { span: 3 }, wrapperCol: { span: 19 }, } } label="概述" > {getFieldDecorator('summary', { })( <Input type="textarea" rows={4} /> )} </FormItem> </Row> </Card> ); formItems.push( <Card key='2' title='标准附件' style={{marginBottom: 20}}> <Row key='4'> <FormItem { ... { labelCol: { span: 3 }, wrapperCol: { span: 19 }, } } label="附件上传" > {getFieldDecorator('resources', { })( <FormUpload deletePath={deleteStandardResourceService} storeName={this.props.storeName}/> )} </FormItem> </Row> </Card> ); return this.renderForm(formItems, (editButton) => { return( <Row style={{marginBottom: 20}}> <Col span={12}> <Row> <Col span={7} /> <Col span={14}> {editButton} </Col> </Row> </Col> </Row> ); }); } }
webapp/pages/all_projects_page.js
bowlofstew/changes
import React from 'react'; import moment from 'moment'; import APINotLoaded from 'es6!display/not_loaded'; import ChangesPage from 'es6!display/page_chrome'; import DisplayUtils from 'es6!display/changes/utils'; import SectionHeader from 'es6!display/section_header'; import { BuildWidget } from 'es6!display/changes/builds'; import { Grid, GridRow } from 'es6!display/grid'; import { Menu1, MenuUtils } from 'es6!display/menus'; import { TimeText } from 'es6!display/time'; import * as api from 'es6!server/api'; import * as utils from 'es6!utils/utils'; var AllProjectsPage = React.createClass({ menuItems: [ 'Latest Project Builds', 'Projects By Repository', 'Plans', 'Plans By Type', 'Jenkins Plans By Master', ], STALE_MAX_AGE: 60*60*24*7, // one week getInitialState: function() { return { projects: null, selectedItem: 'Latest Project Builds', expandedConfigsInPlans: {}, expandedConfigsInPlansByType: {}, } }, componentWillMount: function() { var selected_item_from_hash = MenuUtils.selectItemFromHash( window.location.hash, this.menuItems); if (selected_item_from_hash) { this.setState({ selectedItem: selected_item_from_hash }); } }, componentDidMount: function() { api.fetch(this, { projects: '/api/0/projects/?fetch_extra=1' }); }, render: function() { if (!api.isLoaded(this.state.projects)) { return <APINotLoaded state={this.state.projects} isInline={false} />; } var projects_data = this.state.projects.getReturnedData(); // render menu var selected_item = this.state.selectedItem; var menu = <Menu1 items={this.menuItems} selectedItem={selected_item} onClick={MenuUtils.onClick(this, selected_item)} />; // TODO: what is the snapshot.current option and should I display it? // TODO: ordering var content = null; switch (selected_item) { case 'Latest Project Builds': content = this.renderDefault(projects_data); break; case 'Projects By Repository': content = this.renderByRepo(projects_data); break; case 'Plans': content = this.renderPlans(projects_data); break; case 'Plans By Type': content = this.renderPlansByType(projects_data); break; case 'Jenkins Plans By Master': content = this.renderJenkinsPlansByMaster(projects_data); break; default: throw 'unreachable'; } return <ChangesPage highlight="Projects"> <SectionHeader>Projects</SectionHeader> {menu} <div className="marginTopM">{content}</div> </ChangesPage>; }, /* * Default way to render projects. Shows the latest build. * TODO: do we have any stats we want to show? */ renderDefault: function(projects_data) { var list = [], stale_list = []; _.each(projects_data, p => { var is_stale = false; if (p.lastBuild) { var age = moment.utc().format('X') - moment.utc(p.lastBuild.dateCreated).format('X'); // if there's never been a build for this project, let's not consider // it stale is_stale = age > this.STALE_MAX_AGE; } !is_stale ? list.push(p) : stale_list.push(p); }); var stale_header = stale_list ? <SectionHeader className="marginTopL">Stale Projects (>1 week)</SectionHeader> : null; return <div> {this.renderProjectList(list)} {stale_header} {this.renderProjectList(stale_list)} </div>; }, renderProjectList: function(projects_data) { if (_.isEmpty(projects_data)) { return null; } var grid_data = _.map(projects_data, p => { var widget = null, build_time = null; if (p.lastBuild) { var build = p.lastBuild; widget = <BuildWidget build={build} parentElem={this} />; build_time = <TimeText time={build.dateFinished || build.dateCreated} />; } return [ widget, build_time, p.name, [<a href={"/v2/project/" + p.slug}>Commits</a>, <a className="marginLeftS" href={"/v2/project/" + p.slug + "#ProjectDetails"}> Details </a> ], p.options["project.notes"] ]; }); var headers = ['Last Build', 'When', 'Name', 'Links', 'Notes']; var cellClasses = ['nowrap buildWidgetCell', 'nowrap', 'nowrap', 'nowrap', 'wide']; return <Grid colnum={5} data={grid_data} headers={headers} cellClasses={cellClasses} />; }, /* * Clusters projects together by repo */ renderByRepo: function(projects_data) { var rows = []; var by_repo = _.groupBy(projects_data, p => p.repository.id); _.each(by_repo, repo_projects => { var repo_url = repo_projects[0].repository.url; var repo_name = DisplayUtils.getShortRepoName(repo_url); if (repo_projects.length > 1) { repo_name += ` (${repo_projects.length})`; // add # of projects } var repo_markup = <div> <b>{repo_name}</b> <div className="subText">{repo_url}</div> </div>; var repo_rows = _.map(repo_projects, (p, index) => { var triggers = "Never"; if (p.options["phabricator.diff-trigger"] && p.options["build.commit-trigger"]) { triggers = "Diffs and Commits"; } else if (p.options["phabricator.diff-trigger"]) { triggers = "Only Diffs"; } else if (p.options["build.commit-trigger"]) { triggers = "Only Commits"; } var whitelist = ""; if (p.options['build.file-whitelist']) { whitelist = _.map( utils.split_lines(p.options['build.file-whitelist']), l => <div>{l}</div> ); } return [ index === 0 ? repo_markup : '', <a href={"/v2/project/" + p.slug}>{p.name}</a>, triggers, p.options['build.branch-names'], whitelist, <TimeText time={p.dateCreated} /> ]; }); rows = rows.concat(repo_rows); }); var headers = ['Repo', 'Project', 'Builds for', 'With branches', 'With paths', 'Created']; var cellClasses = ['nowrap', 'nowrap', 'nowrap', 'nowrap', 'wide', 'nowrap']; return <div className="marginBottomL"> <Grid colnum={6} data={rows} headers={headers} cellClasses={cellClasses} /> </div>; }, /* * Renders individual build plans for projects */ renderPlans: function(projects_data) { var rows = []; _.each(projects_data, proj => { var num_plans = proj.plans.length; _.each(proj.plans, (plan, index) => { var proj_name = ""; if (index === 0) { var proj_name = (num_plans > 1) ? <b>{proj.name}{" ("}{num_plans}{")"}</b> : <b>{proj.name}</b>; } if (!plan.steps[0]) { rows.push([ proj_name, plan.name, '', '', <TimeText time={plan.dateModified} /> ]); } else { rows.push([ proj_name, plan.name, <span className="marginRightL">{this.getStepType(plan.steps[0])}</span>, this.getSeeConfigLink(plan.id, 'plans'), <TimeText time={plan.dateModified} /> ]); if (this.isConfigExpanded(plan.id, 'plans')) { rows.push(this.getExpandedConfigRow(plan)); } } }); }); // TODO: snapshot config? var more_link = <span>More{" "} <span style={{fontWeight: 'normal'}}> {"("}{this.getExpandAllLink('plans')}{")"} </span> </span>; var headers = ['Project', 'Plan', 'Implementation', more_link, 'Modified']; var cellClasses = ['nowrap', 'nowrap', 'nowrap', 'wide', 'nowrap']; return <Grid colnum={5} data={rows} headers={headers} cellClasses={cellClasses} />; }, /* * Clusters build plans by type */ renderPlansByType: function(projects_data) { var every_plan = _.flatten( _.map(projects_data, p => p.plans) ); var every_plan_type = _.chain(every_plan) .map(p => p.steps.length > 0 ? this.getStepType(p.steps[0]) : "") .compact() .uniq() // sort, hoisting build types starting with [LXC] to the top .sortBy(t => t.charAt(0) === "[" ? "0" + t : t) .value(); var rows_lists = []; _.each(every_plan_type, type => { // find every plan that matches this type and render it var plan_rows = []; _.each(projects_data, proj => { _.each(proj.plans, (plan, index) => { if (plan.steps.length > 0 && this.getStepType(plan.steps[0]) === type) { plan_rows.push([ null, proj.name, plan.name, this.getSeeConfigLink(plan.id, 'plansByType') ]); if (this.isConfigExpanded(plan.id, 'plansByType')) { plan_rows.push(this.getExpandedConfigRow(plan)); } } }); }); // add plan type label to first row plan_rows[0][0] = <b>{[type, " (", plan_rows.length, ")"]}</b>; rows_lists.push(plan_rows); }); var headers = ['Infrastructure', 'Project Name', 'Plan Name', 'More']; var cellClasses = ['nowrap', 'nowrap', 'nowrap', 'nowrap']; return <Grid colnum={4} data={_.flatten(rows_lists, true)} headers={headers} cellClasses={cellClasses} />; }, renderJenkinsPlansByMaster: function(projects_data) { // keys are jenkins master urls. Values are two lists (master/diff) each of // plans (since we have a separate jenkins_diff_urls) var plans_by_master = {}; var jenkins_fallback_data = {}; // ignore trailing slash for urls var del_trailing_slash = url => url.replace(/\/$/, ''); _.each(projects_data, proj => { _.each(proj.plans, plan => { plan.project = proj; // is there a plan? if (!plan.steps[0]) { return; } // is it a jenkins plan? if (plan.steps[0].name.toLowerCase().indexOf('jenkins') === -1) { return; } if (plan['jenkins_fallback']) { jenkins_fallback_data = plan['jenkins_fallback']; jenkins_fallback_data['fallback_cluster_machines'] = jenkins_fallback_data['fallback_cluster_machines'] ? JSON.stringify(jenkins_fallback_data['fallback_cluster_machines']) : "None"; } var data = JSON.parse(plan.steps[0].data); if (data['jenkins_url']) { _.each(utils.ensureArray(data['jenkins_url']), u => { u = del_trailing_slash(u); plans_by_master[u] = plans_by_master[u] || {}; plans_by_master[u]['master'] = plans_by_master[u]['master'] || []; plans_by_master[u]['master'].push(plan); }); } if (data['jenkins_diff_url']) { _.each(utils.ensureArray(data['jenkins_diff_url']), u => { u = del_trailing_slash(u); plans_by_master[u] = plans_by_master[u] || {}; plans_by_master[u]['diff'] = plans_by_master[u]['diff'] || []; plans_by_master[u]['diff'].push(plan); }); } }); }); var split_urls_for_display = utils.split_start_and_end( _.keys(plans_by_master)); var rows = []; _.each(_.keys(plans_by_master).sort(), url => { var val = plans_by_master[url]; val.master = val.master || []; val.diff = val.diff || []; var is_first_row = true; var first_row_text = <span className="paddingRightM"> <a className="subtle" href={url} target="_blank"> {split_urls_for_display[url][0]} <span className="bb">{split_urls_for_display[url][1]}</span> {split_urls_for_display[url][2]} </a> {" ("}{val.master.length}{"/"}{val.diff.length}{")"} </span>; _.each(val.master, (plan, index) => { rows.push([ is_first_row ? first_row_text : '', index === 0 ? <span className="paddingRightM">Anything</span> : '', plan.name, plan.project.name, <TimeText time={plan.dateModified} /> ]); is_first_row = false; }); _.each(val.diff, (plan, index) => { rows.push([ is_first_row ? first_row_text : '', index === 0 ? <span className="paddingRightM">Diffs-only</span> : '', plan.name, plan.project.name, <TimeText time={plan.dateModified} /> ]); is_first_row = false; }); }); var headers = ['Master', 'Used for', 'Plan', 'Project', 'Modified']; var cellClasses = ['nowrap', 'nowrap', 'nowrap', 'wide', 'nowrap']; return <div> <div className="yellowPre marginBottomM"> Note: this chart only shows explicitly-configured master urls. Here are the fallbacks we use when master is not configured. <div><b>fallback_url: </b>{(jenkins_fallback_data['fallback_url'] || "None")}</div> <div><b>fallback_cluster_machines: </b> {jenkins_fallback_data['fallback_cluster_machines']} </div> </div> <Grid colnum={5} data={rows} headers={headers} cellClasses={cellClasses} /> </div>; }, getSeeConfigLink: function(plan_id, chart_name) { var state_key = this.getConfigStateKey(chart_name); var onClick = ___ => { this.setState( utils.update_key_in_state_dict( state_key, plan_id, !this.state[state_key][plan_id]) ); } var text = this.state[state_key][plan_id] ? 'Hide Config' : 'See Config'; return <a onClick={onClick}>{text}</a>; }, getExpandAllLink: function(chart_name) { var state_key = this.getConfigStateKey(chart_name); var onClick = ___ => { if (this.state[state_key]['all']) { // delete all variables that expand a config this.setState({ [ state_key ]: {}}); } else { this.setState( utils.update_key_in_state_dict(state_key, 'all', true) ); } }; var text = this.state[state_key]['all'] ? 'Collapse All' : 'Expand All'; return <a onClick={onClick}>{text}</a>; }, isConfigExpanded: function(plan_id, chart_name) { var state_key = this.getConfigStateKey(chart_name); return this.state[state_key][plan_id] || this.state[state_key]['all']; }, getConfigStateKey: function(chart_name) { switch (chart_name) { case 'plans': return 'expandedConfigsInPlans'; case 'plansByType': return 'expandedConfigsInPlansByType'; default: throw `unknown chart name ${chart_name}`; }; }, getExpandedConfigRow: function(plan) { var build_timeout = plan.steps[0].options['build.timeout']; var build_timeout_markup = null; if (build_timeout !== undefined) { build_timeout_markup = [ <span className="lb">Build Timeout: </span>, build_timeout ]; } return GridRow.oneItem( <div> <pre className="yellowPre"> {plan.steps[0] && plan.steps[0].data} </pre> {build_timeout_markup} </div> ); }, getStepType: function(step) { var is_lxc = false; _.each(utils.split_lines(step.data), line => { // look for a "build_type": "lxc" line if (line.indexOf("build_type") >= 0 && line.indexOf("lxc") >= 0) { is_lxc = true; } }); var is_jenkins_lxc = is_lxc && step.name.indexOf("Jenkins") >= 0; return is_jenkins_lxc ? "[LXC] " + step.name : step.name; } }); export default AllProjectsPage;
frontend/app/components/StatusBar/index.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import Snackbar from '@material-ui/core/Snackbar' export default class StatusBar extends React.Component { constructor(props) { super(props) this.state = { open: true, } } handleRequestClose = () => { this.setState({ open: false, }) } // componentDidUpdate() { // if (this.state.open !== true) { // this.setState({ // open: true, // }) // } // } render() { if (this.props.message) { return ( <div> <Snackbar open={this.state.open} message={this.props.message} autoHideDuration={5000} onClose={this.handleRequestClose} /> </div> ) } return <div /> } }
resources/js/components/FormInput/FileUploadInput.js
DoSomething/northstar
import React from 'react'; import PropTypes from 'prop-types'; /** * Base file upload input. */ const FileUploadInput = ({ accept, className, clearErrors, id, name, refs, setData, }) => { function handleChange(event) { clearErrors(event.target.name); setData(event.target.name, event.target.files[0]); } return ( <input accept={accept} className={className} id={id} name={name || id} onChange={handleChange} ref={refs} type="file" /> ); }; FileUploadInput.propTypes = { /** * What file types should the input accept? */ accept: PropTypes.string.isRequired, /** * Classes to style the input element. */ className: PropTypes.string, /** * Method for clearing input errors. */ clearErrors: PropTypes.func.isRequired, /** * Identifier attribute for the input element. */ id: PropTypes.string.isRequired, /** * Name attribute for the input element; will default to the same value as ID if none provided. */ name: PropTypes.string, /** * Method for setting value for data when input provided. */ setData: PropTypes.func.isRequired, }; FileUploadInput.defaultProps = { className: null, name: null, }; export default FileUploadInput;
src/Tab/Item.js
szchenghuang/react-mdui
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; class Item extends React.Component { render() { return null; } } Item.propTypes = { children: PropTypes.node, id: PropTypes.string, icon: PropTypes.node, label: PropTypes.string, ripple: PropTypes.any, active: PropTypes.any }; Item.defaultProps = { ripple: true }; export default Item;
imports/ui/components/Loading/Loading.js
lazygalaxy/lazybat-seed-meteorjs
import React from 'react'; const Loading = () => ( <div className="Loading"> <svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg" stroke="#4285F4"> <g fill="none" fillRule="evenodd" strokeWidth="2"> <circle cx="22" cy="22" r="1"> <animate attributeName="r" begin="0s" dur="1.8s" values="1; 20" calcMode="spline" keyTimes="0; 1" keySplines="0.165, 0.84, 0.44, 1" repeatCount="indefinite" /> <animate attributeName="stroke-opacity" begin="0s" dur="1.8s" values="1; 0" calcMode="spline" keyTimes="0; 1" keySplines="0.3, 0.61, 0.355, 1" repeatCount="indefinite" /> </circle> <circle cx="22" cy="22" r="1"> <animate attributeName="r" begin="-0.9s" dur="1.8s" values="1; 20" calcMode="spline" keyTimes="0; 1" keySplines="0.165, 0.84, 0.44, 1" repeatCount="indefinite" /> <animate attributeName="stroke-opacity" begin="-0.9s" dur="1.8s" values="1; 0" calcMode="spline" keyTimes="0; 1" keySplines="0.3, 0.61, 0.355, 1" repeatCount="indefinite" /> </circle> </g> </svg> </div> ); export default Loading;
src/components/Header/Header.js
rameshrr/dicomviewer
/** * 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 logoUrl from './logo-small.png'; import logoUrl2x from './logo-small@2x.png'; class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation /> <Link className={s.brand} to="/"> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" /> <span className={s.brandTxt}>Your Company</span> </Link> <div className={s.banner}> <h1 className={s.bannerTitle}>React</h1> <p className={s.bannerDesc}>Complex web apps made easy</p> </div> </div> </div> ); } } export default withStyles(s)(Header);
components/BackendWidgetComponent.js
ExtPoint/yii2-frontend
import React from 'react'; import {Provider} from 'react-redux'; import domready from 'domready'; import loadJs from 'load-js'; import ReactDOM from 'react-dom'; import _trimStart from 'lodash-es/trimStart'; export default class BackendWidgetComponent { constructor(store) { this.store = store || null; this.scripts = []; this.toRender = []; this._widgets = {}; setTimeout(() => { loadJs( this.scripts.map(url => ({ url, async: true, })) ) .then(() => { domready(() => { this.toRender.forEach(args => this.render.apply(this, args)); }); }); }); } register(name, func) { name = _trimStart(name, '\\'); if (arguments.length === 1) { // Decorator return func => { this._widgets[name] = func; }; } else { this._widgets[name] = func; return func; } } render(elementId, name, props) { if (process.env.NODE_ENV !== 'production') { window.__snapshot = (window.__snapshot || []).concat({ widget: { elementHtml: document.getElementById(elementId).innerHTML, elementId, name, props, }, }); } const WidgetComponent = this._widgets[_trimStart(name, '\\')]; ReactDOM.render( <Provider store={this.store}> <WidgetComponent {...props} /> </Provider>, document.getElementById(elementId) ); } }
app/components/Report/BizList.js
Bullseyed/Bullseye
import React from 'react' import { Row, Col, Collection, CollectionItem, Modal, Icon } from 'react-materialize' import { connect } from 'react-redux' const BizList = (props) => { return ( <Row> <Row> <b> Nearby Businesses: </b> </Row> <Row style={{ paddingTop: 0, paddingBottom: 0 }}> <Col s={6}> <b> Name </b> </Col> <Col s={2}> <b> Price </b> </Col> <Col s={2}> <b> Rating </b> </Col> <Col s={2}> <b> Distance </b> </Col> </Row> {props.rests.length && <div> <a href="#" style={{color: 'black'}}> {props.rests.map(rest => { return rest.distance <= props.radius ? <Row key={rest.id} style={{ paddingTop: 0, paddingBottom: 0, marginBottom: 0 }}> <Modal header={rest.name} trigger={ <Row> <Col s={6}> {rest.name} </Col> <Col s={2}> {rest.price} </Col> <Col s={2}> {`${rest.rating}/5`} </Col> <Col s={2}> { props.report.distanceMeasurement === 'miles' ? `${(+rest.distance / 1609.344).toFixed(2)} mi` : `${(+rest.distance / 1000).toFixed(2)} km`} </Col> </Row> }> <Row> <Col s={6}> <img src={rest.image_url} style={{ width: "100%", height: "100%" }} /> </Col> <Col s={6}> <p> <b> Distance: </b> {rest.distance} </p> <p> <b> Address: </b>{rest.location.display_address.join(', ')} </p> <p> <b> Phone Number:</b> {rest.phone} </p> <p> <b> Rating: </b>{rest.rating} </p> <p> <b> Price Rating:</b> {rest.price} </p> </Col> </Row> </Modal> </Row> : null })} </a> </div> } </Row> ) } const mapStateToProps = ({ rests, radius, report }) => ({ rests, radius, report }) export default connect(mapStateToProps, null)(BizList)
components/PackageRepoBranchName.js
loggur/branches
import React, { Component } from 'react'; import provide from 'react-redux-provide'; import onClickToggle from '../common/onClickToggle.js'; import { getRepoTree, getDirtyMap, tree, dirty, toggle, open, theme, repoApi, repoKey, repoName, branchName, fullPath, children } from '../common/propTypes.js'; import Limbs from './Limbs.js'; import CommitIcon from './CommitIcon.js'; @provide({ getRepoTree, getDirtyMap, tree, dirty, toggle, open, theme }) export default class PackageRepoBranchName extends Component { static propTypes = { repoApi, repoKey, repoName, branchName, fullPath, children }; componentDidMount() { const { repoApi, repoKey, getRepoTree, getDirtyMap, branchName } = this.props; getRepoTree(repoApi, repoKey, branchName); getDirtyMap(repoKey, branchName); } onClick = onClickToggle; render() { const props = this.props; const { tree, repoApi, repoKey, dirty, repoName, branchName, fullPath, open, theme, children } = props; const classes = props.theme.sheet.classes || {}; const { repoBranch, repoBranchName, repoBranchIcon } = classes; const imgSrc = open ? 'folder-open.png' : 'folder-closed.png'; const nameClasses = [repoBranchName]; let commitIcon; if (dirty) { nameClasses.push(classes.dirtyRepoBranch); commitIcon = ( <CommitIcon fullPath={fullPath} theme={theme} /> ); } return ( <div className={repoBranch} onClick={::this.onClick}> <div className={nameClasses.join(' ')}> <img className={repoBranchIcon} src={theme.imagesDir+imgSrc} /> <span>{repoName+'@'+branchName}</span> {commitIcon} </div> <Limbs fullPath={fullPath} branchName={branchName} repoApi={repoApi} repoKey={repoKey} tree={tree} /> </div> ); } }
src/assets/js/pages/carousel_sample.js
task-k/react_prototype
import React from 'react' import {render} from 'react-dom' import {Provider} from 'react-redux' import App from '../component/carousel' render( <Provider> <App/> </Provider>, document.getElementById("root") )
indico/web/client/js/jquery/widgets/jinja/permissions_widget.js
indico/indico
// This file is part of Indico. // Copyright (C) 2002 - 2022 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import React from 'react'; import ReactDOM from 'react-dom'; import {GroupSearch, UserSearch} from 'indico/react/components/principals/Search'; import {PrincipalType} from 'indico/react/components/principals/util'; import {FavoritesProvider} from 'indico/react/hooks'; import {Translate} from 'indico/react/i18n'; import Palette from 'indico/utils/palette'; (function($) { const FULL_ACCESS_PERMISSIONS = '_full_access'; const READ_ACCESS_PERMISSIONS = '_read_access'; $.widget('indico.permissionswidget', { options: { objectType: null, isUnlisted: null, permissionsInfo: null, hiddenPermissions: null, hiddenPermissionsInfo: null, }, _update() { // Sort entries aphabetically and by type this.data = _.chain(this.data) .sortBy(item => item[0].name || item[0].id) .sortBy(item => item[0]._type) .value(); // Sort permissions alphabetically this.data.forEach(item => { item[1].sort(); }); this.$dataField.val(JSON.stringify(this.data)); this.element.trigger('change'); }, _renderRoleCode(code, color) { return $('<span>', { class: 'role-code', text: code, css: { borderColor: `#${color}`, color: `#${color}`, }, }); }, _renderLabel(principal) { const $labelBox = $('<div>', {class: 'label-box flexrow f-a-center'}); const type = principal._type; if (type === 'EventRole') { $labelBox.append(this._renderEventRoleLabel(principal)); } else if (type === 'CategoryRole') { $labelBox.append(this._renderCategoryRoleLabel(principal)); } else { $labelBox.append(this._renderOtherLabel(principal, type)); } return $labelBox; }, _renderEventRoleLabel(principal) { const $text = $('<span>', { 'class': 'text-normal entry-label', 'text': principal.name, 'data-tooltip-text': principal.name, }); const $code = this._renderRoleCode(principal.code, principal.color); return [$code, $text]; }, _renderCategoryRoleLabel(principal) { const text = principal.name; const extraText = principal.category; const $code = this._renderRoleCode(principal.code, principal.color); const tooltip = `${text} (${extraText})`; const textDiv = $('<div>', { 'class': 'text-normal entry-label', 'data-tooltip-text': tooltip, }); textDiv.append($('<span>', {text})); textDiv.append('<br>'); textDiv.append($('<span>', {class: 'text-not-important entry-label-extra', text: extraText})); return [$code, textDiv]; }, _renderOtherLabel(principal, type) { let iconClass, extraText; if (type === 'Avatar') { iconClass = 'icon-user'; extraText = principal.email; } else if (type === 'Email') { iconClass = 'icon-mail'; } else if (type === 'DefaultEntry' && principal.id === 'anonymous') { iconClass = 'icon-question'; } else if (type === 'IPNetworkGroup') { iconClass = 'icon-lan'; } else if (type === 'RegistrationForm') { iconClass = 'icon-ticket'; } else if (type === 'LocalGroup') { iconClass = 'icon-users'; } else if (type === 'MultipassGroup') { iconClass = 'icon-users'; extraText = principal.provider_title; } else { iconClass = 'icon-users'; } const text = principal.name; const tooltip = extraText ? `${text} (${extraText})` : text; const textDiv = $('<div>', { 'class': 'text-normal entry-label', 'data-tooltip-text': tooltip, }); textDiv.append($('<span>', {text})); if (extraText) { textDiv.append('<br>'); textDiv.append( $('<span>', {class: 'text-not-important entry-label-extra', text: extraText}) ); } return [$('<span>', {class: `entry-icon ${iconClass}`}), textDiv]; }, _renderPermissions(principal, permissions) { const $permissions = $('<div>', {class: 'permissions-box flexrow f-a-center f-self-stretch'}); const $permissionsList = $('<ul>').appendTo($permissions); // When full access is enabled, always show read access if ( _.contains(permissions, FULL_ACCESS_PERMISSIONS) && !_.contains(permissions, READ_ACCESS_PERMISSIONS) ) { permissions.push(READ_ACCESS_PERMISSIONS); if (principal._type !== 'DefaultEntry' && principal._type !== 'AdditionalUsers') { this._updateItem(principal, permissions); } } permissions.forEach(item => { const permissionInfo = this.options.permissionsInfo[item]; const applyOpacity = item === READ_ACCESS_PERMISSIONS && _.contains(permissions, FULL_ACCESS_PERMISSIONS) && principal._type !== 'DefaultEntry'; const cssClasses = (applyOpacity ? 'disabled ' : '') + (permissionInfo.color ? `color-${permissionInfo.color} ` : '') + (permissionInfo.css_class ? `${permissionInfo.css_class} ` : ''); $permissionsList.append( $('<li>', { class: `i-label bold ${cssClasses}`, title: permissionInfo.description, }).append(permissionInfo.title) ); }); if (principal._type !== 'DefaultEntry' && principal._type !== 'AdditionalUsers') { $permissions.append(this._renderPermissionsButtons(principal, permissions)); } return $permissions; }, _renderPermissionsButtons(principal, permissions) { const $buttonsGroup = $('<div>', {class: 'group flexrow'}); $buttonsGroup.append( this._renderEditBtn(principal, permissions), this._renderDeleteBtn(principal) ); return $buttonsGroup; }, _renderEditBtn(principal, permissions) { if (principal._type === 'IPNetworkGroup' || principal._type === 'RegistrationForm') { const title = { IPNetworkGroup: $T.gettext('IP networks cannot have management permissions'), RegistrationForm: $T.gettext('Registrants cannot have management permissions'), }[principal._type]; return $('<button>', { type: 'button', class: 'i-button text-color borderless icon-only icon-edit disabled', title, }); } else { return $('<button>', { 'type': 'button', 'class': 'i-button text-color borderless icon-only icon-edit', 'data-href': build_url(Indico.Urls.PermissionsDialog, {type: this.options.objectType}), 'data-title': $T.gettext('Assign Permissions'), 'data-method': 'POST', 'data-ajax-dialog': '', 'data-params': JSON.stringify({principal: JSON.stringify(principal), permissions}), }); } }, _renderDeleteBtn(principal) { const self = this; return $('<button>', { 'type': 'button', 'class': 'i-button text-color borderless icon-only icon-remove', 'data-principal': JSON.stringify(principal), }).on('click', function() { const $this = $(this); let confirmed; if (principal._type === 'Avatar' && principal.id === $('body').data('user-id')) { const title = $T.gettext("Delete entry '{0}'".format(principal.name || principal.id)); const message = $T.gettext('Are you sure you want to remove yourself from the list?'); confirmed = confirmPrompt(message, title); } else { confirmed = $.Deferred().resolve(); } confirmed.then(() => { self._updateItem($this.data('principal'), []); }); }); }, _renderItem(item) { const $item = $('<li>', {class: 'flexrow f-a-center'}); const [principal, permissions] = item; $item.append(this._renderLabel(principal)); $item.append(this._renderPermissions(principal, permissions)); $item.toggleClass(`disabled ${principal.id}`, principal._type === 'DefaultEntry'); return $item; }, _renderHiddenPermissions(item) { const $item = $('<li>', { class: 'flexrow f-a-center', }); const [principal, description, $permissionsList] = item; $permissionsList.hide(); const $dropdownButton = $('<button>', { type: 'button', class: 'i-button text-color borderless icon-only icon-expand hidden-permissions-icon', }).on('click', () => { $permissionsList.toggle(); $dropdownButton.toggleClass('icon-expand icon-collapse'); }); const $hiddenPermissionsDiv = $('<div>', { class: 'permissions-box f-a-center f-self-stretch', }); const $descriptionDiv = $('<div>', {class: 'flexrow f-a-center'}); $descriptionDiv.append( $('<div>', {class: 'hidden-permissions-description', text: description}) ); $descriptionDiv.append($dropdownButton); $hiddenPermissionsDiv.append($descriptionDiv); $hiddenPermissionsDiv.append($permissionsList); $item.append(this._renderLabel(principal).toggleClass(`disabled ${principal.id}`)); $item.append($hiddenPermissionsDiv); return $item; }, _renderHiddenPermissionsList(hiddenUserPermissions, permissionsInfo) { const $list = $('<ul>', {class: 'hidden-permissions-list'}); hiddenUserPermissions.forEach(([name, perms]) => { const permissionList = perms .map(x => permissionsInfo[x]) .filter(x => x !== null) .join(', '); const $user = $('<strong />', {text: name}); const $permissions = `: ${permissionList}`; const $entry = $('<li>') .append($user) .append($permissions); $list.append($entry); }); return $list; }, _renderDropdown($dropdown, getText = null) { $dropdown.children(':not(.default)').remove(); $dropdown.parent().dropdown({ selector: '.js-dropdown', }); const $dropdownLink = $dropdown.prev('.js-dropdown'); const items = $dropdown.data('items'); const isRoleDropdown = $dropdown.hasClass('entry-role-dropdown'); items.forEach(item => { if (this._findEntryIndex(item) === -1) { if (isRoleDropdown) { $dropdown.find('.separator').before(this._renderDropdownItem(item, getText)); } else { $dropdown.append(this._renderDropdownItem(item, getText)); } } }); if (isRoleDropdown) { const isEmpty = !$dropdown.children().not('.default').length; $('.entry-role-dropdown .separator').toggleClass('hidden', isEmpty); } else if (!$dropdown.children().length) { $dropdownLink.addClass('disabled').attr('title', $T.gettext('All options have been added')); } else { $dropdownLink.removeClass('disabled'); } }, _renderDropdownItem(principal, getText) { const self = this; const $dropdownItem = $('<li>', { 'class': 'entry-item', 'data-principal': JSON.stringify(principal), }); const $itemContent = $('<a>'); if (principal._type === 'EventRole' || principal._type === 'CategoryRole') { $itemContent.append( this._renderRoleCode(principal.code, principal.color).addClass('dropdown-icon') ); } const $text = $('<span>', {text: getText ? getText(principal.name) : principal.name}); $dropdownItem.append($itemContent.append($text)).on('click', function() { // Grant read access by default self._addItems([$(this).data('principal')], [READ_ACCESS_PERMISSIONS]); }); return $dropdownItem; }, _renderDuplicatesTooltip(idx) { this.$permissionsWidgetList .find('>li') .not('.disabled') .eq(idx) .qtip({ content: { text: $T.gettext('This entry was already added'), }, show: { ready: true, effect() { $(this).fadeIn(300); }, }, hide: { event: 'unfocus click', }, events: { hide() { $(this).fadeOut(300); $(this).qtip('destroy'); }, }, position: { my: 'center left', at: 'center right', }, style: { classes: 'qtip-warning', }, }); }, _render() { this.$permissionsWidgetList.empty(); this.data.forEach(item => { this.$permissionsWidgetList.append(this._renderItem(item)); }); // Add default entries if (!this.options.isUnlisted) { const anonymous = [ {_type: 'DefaultEntry', name: $T.gettext('Anonymous'), id: 'anonymous'}, [READ_ACCESS_PERMISSIONS], ]; this.$permissionsWidgetList.append(this._renderItem(anonymous)); } if (this.options.hiddenPermissions.length > 0) { const additionalPermissions = [ { _type: 'AdditionalUsers', name: $T.gettext('Additional users'), id: 'additional', }, $T .ngettext( '{0} user has implicit read access due to other roles', '{0} users have implicit read access due to other roles', this.options.hiddenPermissions.length ) .format(this.options.hiddenPermissions.length), this._renderHiddenPermissionsList( this.options.hiddenPermissions, this.options.hiddenPermissionsInfo ), ]; this.$permissionsWidgetList.append(this._renderHiddenPermissions(additionalPermissions)); } let managersTitle; if (!this.options.isUnlisted && this.options.objectType === 'event') { managersTitle = $T.gettext('Category Managers'); } else if (this.options.objectType === 'category') { managersTitle = $T.gettext('Parent Category Managers'); } else if (['session', 'contribution'].includes(this.options.objectType)) { managersTitle = $T.gettext('Event Managers'); } if (managersTitle) { const managers = [{_type: 'DefaultEntry', name: managersTitle}, [FULL_ACCESS_PERMISSIONS]]; this.$permissionsWidgetList.prepend(this._renderItem(managers)); this.$permissionsWidgetList.find('.anonymous').toggle(!this.isEventProtected); } if (this.$eventRoleDropdown.length) { this._renderDropdown(this.$eventRoleDropdown); } if (this.$categoryRoleDropdown.length) { this._renderDropdown(this.$categoryRoleDropdown); } if (this.$ipNetworkDropdown.length) { this._renderDropdown(this.$ipNetworkDropdown); } if (this.$registrationFormDropdown.length) { this._renderDropdown(this.$registrationFormDropdown, name => $T.gettext('Registrants in "{0}"').format(name) ); } }, _findEntryIndex(principal) { return _.findIndex(this.data, item => item[0].identifier === principal.identifier); }, _updateItem(principal, newPermissions) { const idx = this._findEntryIndex(principal); if (newPermissions.length) { this.data[idx][1] = newPermissions; } else { this.data.splice(idx, 1); } this._update(); this._render(); }, _addItems(principals, permissions) { const news = []; const repeated = []; principals.forEach(principal => { const idx = this._findEntryIndex(principal); if (idx === -1) { this.data.push([principal, permissions]); news.push(principal); } else { repeated.push(principal); } }); this._update(); this._render(); news.forEach(principal => { this.$permissionsWidgetList .children('li:not(.disabled)') .eq(this._findEntryIndex(principal)) .effect('highlight', {color: Palette.highlight}, 'slow'); }); repeated.forEach(principal => { this._renderDuplicatesTooltip(this._findEntryIndex(principal)); }); }, _create() { this.$permissionsWidgetList = this.element.find('.permissions-widget-list'); this.$dataField = this.element.find('input[type=hidden]'); this.$eventRoleDropdown = this.element.find('.entry-role-dropdown'); this.$categoryRoleDropdown = this.element.find('.entry-category-role-dropdown'); this.$ipNetworkDropdown = this.element.find('.entry-ip-network-dropdown'); this.$registrationFormDropdown = this.element.find('.entry-reg-form-dropdown'); this.data = JSON.parse(this.$dataField.val()); this._update(); this._render(); // Manage changes on the permissions dialog this.element.on('indico:permissionsChanged', (evt, permissions, principal) => { this._updateItem(principal, permissions); }); // Manage changes on the event protection mode field this.element.on('indico:protectionModeChanged', (evt, isProtected) => { this.isEventProtected = isProtected; this._render(); }); // Manage adding users/groups to the acl const userSearchTrigger = triggerProps => ( <a className="i-button" {...triggerProps}> <Translate>User</Translate> </a> ); const groupSearchTrigger = triggerProps => ( <a className="i-button" {...triggerProps}> <Translate>Group</Translate> </a> ); const existing = JSON.parse(this.$dataField.val()).map(e => e[0].identifier); ReactDOM.render( <FavoritesProvider> {([favorites]) => ( <> <UserSearch withExternalUsers favorites={favorites} existing={existing.filter(e => e.startsWith('User'))} onAddItems={e => { const items = e.map(({identifier, userId, name, firstName, lastName}) => ({ identifier, name, id: userId, familyName: lastName, firstName, _type: 'Avatar', })); this._addItems(items, [READ_ACCESS_PERMISSIONS]); }} triggerFactory={userSearchTrigger} /> <GroupSearch existing={existing.filter(e => e.startsWith('Group'))} onAddItems={e => { const items = e.map(({identifier, name, type, provider}) => { let id; if (type === PrincipalType.localGroup) { const splitIdentifier = identifier.split(':'); id = splitIdentifier[splitIdentifier.length - 1]; } else { id = name; } return { identifier, name, provider, _type: type === PrincipalType.localGroup ? 'LocalGroup' : 'MultipassGroup', id, }; }); this._addItems(items, [READ_ACCESS_PERMISSIONS]); }} triggerFactory={groupSearchTrigger} /> </> )} </FavoritesProvider>, document.getElementById('js-add-user-group') ); // Manage the creation of new roles $('.js-new-role').on('ajaxDialog:closed', (evt, data) => { if (data && data.role) { this.$eventRoleDropdown.data('items').push(data.role); this._addItems([data.role], [READ_ACCESS_PERMISSIONS]); } }); // Apply ellipsis + tooltip on long names this.$permissionsWidgetList.on('mouseenter', '.entry-label', function() { const $this = $(this); if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) { $this.attr('title', $this.attr('data-tooltip-text')); } }); }, }); })(jQuery);
index.js
ranveerching/react-native-custom-snackbar
import React, { Component } from 'react'; import { View, Text, Animated, Image, TouchableOpacity, StyleSheet } from 'react-native'; import PropTypes from 'prop-types'; class SnackBar extends Component { constructor() { super(); this.animatedValue = new Animated.Value(60); this.snackBarShown = false; this.snackBarHidden = true; this.state = { message: '' }; } componentWillUnmount() { clearTimeout(this.timerID); } show(message="Default Message...", duration=3000) { if( this.snackBarShown === false ) { this.setState({ message: message }); this.snackBarShown = true; Animated.timing ( this.animatedValue, { toValue: 0, duration: 350 } ).start(this.hide(duration)); } } hide = (duration) => { this.timerID = setTimeout(() => { if(this.snackBarHidden === true) { this.snackBarHidden = false; Animated.timing ( this.animatedValue, { toValue: 60, duration: 350 } ).start(() => { this.snackBarHidden = true; this.snackBarShown = false; clearTimeout(this.timerID); }) } }, duration); } closeSnackBar = () => { if(this.snackBarHidden === true) { this.snackBarHidden = false; clearTimeout(this.timerID); Animated.timing ( this.animatedValue, { toValue: 60, duration: 350 } ).start(() => { this.snackBarShown = false; this.snackBarHidden = true; }); } } render() { return( <Animated.View style = {[{ transform: [{ translateY: this.animatedValue }], backgroundColor: this.props.snackBarBackColor }, styles.animatedView ]}> <Text numberOfLines = { 2 } style = {[ styles.snackBarText, { color: this.props.snackBarTextColor } ]}>{ this.state.message }</Text> <TouchableOpacity onPress = { this.closeSnackBar } activeOpacity = { 1 } style = { styles.closeBtn }> { (this.props.closeText === undefined || this.props.closeText === '') ? ( <Image source = { require('./assets/close.png') } style = {[ styles.closeBtnImage, { tintColor: this.props.imageColor }]} /> ) : ( <Text style = {{ color: this.props.closeTextColor, fontWeight: 'bold' }}>{ this.props.closeText.toUpperCase() }</Text> ) } </TouchableOpacity> </Animated.View> ); } } const styles = StyleSheet.create( { animatedView: { position: 'absolute', left: 0, bottom: 0, right: 0, height: 60, flexDirection: 'row', alignItems: 'center', paddingLeft: 10, paddingRight: 75 }, snackBarText: { fontSize: 15 }, closeBtn: { position: 'absolute', right: 10, justifyContent: 'center', padding: 5 }, closeBtnImage: { resizeMode: 'contain', width: 23, height: 23 } }); SnackBar.propTypes = { snackBarBackColor: PropTypes.string, closeText: PropTypes.string, closeTextColor: PropTypes.string, snackBarTextColor: PropTypes.string, imageColor: PropTypes.string } SnackBar.defaultProps = { snackBarBackColor: 'rgba(0,0,0,0.8)', closeTextColor: 'rgb(253,85,82)', snackBarTextColor: 'white', imageColor: 'rgb(253,85,82)' }; module.exports = SnackBar;
src/shared/components/idme/idme.js
hollomancer/operationcode_frontend
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { openIDME = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${ config.host }/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> {/* eslint-disable jsx-a11y/click-events-have-key-events */} <span className={styles.authbtn} role="link" onClick={this.openIDME} tabIndex={0}> <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
src/icons/IosPaper.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosPaper extends React.Component { render() { if(this.props.bare) { return <g> <path d="M112,64v16v32v288H96V112H64v305.143C64,434.157,77.843,448,94.857,448h322.285C434.157,448,448,434.157,448,417.143V64H112 z M160,112h128v16H160V112z M160,272h192v16H160V272z M400,368H160v-16h240V368z M400,208H160v-16h240V208z"></path> </g>; } return <IconBase> <path d="M112,64v16v32v288H96V112H64v305.143C64,434.157,77.843,448,94.857,448h322.285C434.157,448,448,434.157,448,417.143V64H112 z M160,112h128v16H160V112z M160,272h192v16H160V272z M400,368H160v-16h240V368z M400,208H160v-16h240V208z"></path> </IconBase>; } };IosPaper.defaultProps = {bare: false}
cm19/ReactJS/your-first-react-app-exercises-master/exercise-16/complete/theme/Provider.js
Brandon-J-Campbell/codemash
import React from 'react'; import ThemeContext from './context'; export default class ThemeProvider extends React.Component { state = { theme: 'purple', }; handleThemeChange = () => { this.setState(prevState => ({ theme: prevState.theme === 'green' ? 'purple' : 'green', })); }; render() { const data = { theme: this.state.theme, onThemeChanged: this.handleThemeChange, }; return ( <ThemeContext.Provider value={data}> {this.props.children} </ThemeContext.Provider> ); } }
src/mixins/style-propable.js
SBP07/frontend
import React from 'react'; import ImmutabilityHelper from '../utils/immutability-helper'; import Styles from '../utils/styles'; // This mixin isn't necessary and will be removed in v0.11 /** * @params: * styles = Current styles. * props = New style properties that will override the current style. */ export default class StylePropable { static propTypes: { style: React.PropTypes.object } // Moved this function to ImmutabilityHelper.merge mergeStyles() { return ImmutabilityHelper.merge.apply(this, arguments); } // Moved this function to /utils/styles.js mergeAndPrefix() { return Styles.mergeAndPrefix.apply(this, arguments); } // prepareStyles is used to merge multiple styles, make sure they are flipped to rtl // if needed, and then autoprefix them. It should probably always be used instead of // mergeAndPrefix. // // Never call this on the same style object twice. As a rule of thumb, // only call it when passing style attribute to html elements. // If you call it twice you'll get a warning anyway. prepareStyles() { return Styles.prepareStyles.apply(Styles, [(this.state && this.state.muiTheme) || this.context.muiTheme].concat([].slice.apply(arguments))); } }
src/heavyweightcomponents/propmonger.js
bhuvanmalik007/mission-admission
/* eslint-disable react/prop-types */ import React from 'react' const propMonger = ({ swallowProps = [] } = {}) => WrappedComponent => { const Wrapper = ({ children, ...props }) => { swallowProps.forEach(propName => { delete props[propName] }) return <WrappedComponent {...props}>{children}</WrappedComponent> } return Wrapper } export default propMonger
src/routes.js
sallen450/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/native/me/MePage.js
reedlaw/read-it
// @flow import type { State, User } from '../../common/types'; import React from 'react'; import SignOut from '../auth/SignOut'; import getUserPhotoUrl from '../../common/users/getUserPhotoUrl'; import { Box, Text } from '../../common/components'; import { Image } from 'react-native'; import { Redirect } from 'react-router'; import { connect } from 'react-redux'; type MePageProps = { viewer: ?User, }; const MePage = ( { viewer, }: MePageProps, ) => !viewer ? <Redirect to="/" /> : <Box alignItems="center"> <Text marginTop={4} size={1}> {viewer.displayName} </Text> <Box as={Image} source={{ uri: getUserPhotoUrl(viewer) }} width={4} height={4} marginVertical={2} /> <SignOut /> </Box>; export default connect((state: State) => ({ viewer: state.users.viewer, }))(MePage);
site/src/pages/vue/Home.js
appbaseio/reactivesearch
import React from 'react'; import config from './../../constants/config/home/vue'; import Home from './../../components/Home'; import theme from './../../constants/theme/vue'; export default () => <Home config={config} theme={theme} />;
react-flux-mui/js/material-ui/src/svg-icons/av/forward-30.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward30 = (props) => ( <SvgIcon {...props}> <path d="M9.6 13.5h.4c.2 0 .4-.1.5-.2s.2-.2.2-.4v-.2s-.1-.1-.1-.2-.1-.1-.2-.1h-.5s-.1.1-.2.1-.1.1-.1.2v.2h-1c0-.2 0-.3.1-.5s.2-.3.3-.4.3-.2.4-.2.4-.1.5-.1c.2 0 .4 0 .6.1s.3.1.5.2.2.2.3.4.1.3.1.5v.3s-.1.2-.1.3-.1.2-.2.2-.2.1-.3.2c.2.1.4.2.5.4s.2.4.2.6c0 .2 0 .4-.1.5s-.2.3-.3.4-.3.2-.5.2-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.4-.1-.6h.8v.2s.1.1.1.2.1.1.2.1h.5s.1-.1.2-.1.1-.1.1-.2v-.5s-.1-.1-.1-.2-.1-.1-.2-.1h-.6v-.7zm5.7.7c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.9-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5zM4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8z"/> </SvgIcon> ); AvForward30 = pure(AvForward30); AvForward30.displayName = 'AvForward30'; AvForward30.muiName = 'SvgIcon'; export default AvForward30;
src/parser/warlock/destruction/CONFIG.js
FaideWW/WoWAnalyzer
import React from 'react'; import { Chizu } from 'CONTRIBUTORS'; import retryingPromise from 'common/retryingPromise'; import SPECS from 'game/SPECS'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [Chizu], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.0.1', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Hello fellow Netherlords! With some help from <strong>Motoko</strong> from Warlock Discord, we've put together this tool to help you improve your gameplay. It should be fine for you generally, but it will be even more useful in an expert's hands. <br /> <br /> If you have any questions about Warlocks, feel free to pay a visit to <a href="https://discord.gg/BlackHarvest" target="_blank" rel="noopener noreferrer">Council of the Black Harvest Discord</a>&nbsp; or <a href="http://lockonestopshop.com" target="_blank" rel="noopener noreferrer">Lock One Stop Shop</a>, if you'd like to discuss anything about this analyzer, message me @Chizu#2873 on WoWAnalyzer Discord. </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/LYXJDPpyN68QaWrm/24-Heroic+Vectis+-+Kill+(7:13)/9-Jeanvoeruler', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.DESTRUCTION_WARLOCK, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "DestructionWarlock" */).then(exports => exports.default)), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
src/app/src/components/InstructorPreferences.js
istreight/eggbeatr
/** * FILENAME: Instructors.js * AUTHOR: Isaac Streight * START DATE: October 25th, 2016 * * This file contains the Intructors class for * the collection of instructors for the lesson * calendar web application. */ import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import Modal from 'utils/Modal'; import Anchor from 'utils/Anchor'; import EditButton from 'specializations/EditButton'; class InstructorPreferences extends React.Component { constructor(props) { super(props); this.state = { ...props.initData }; this.selectedInstructor = Object.keys(props.initData.data)[0]; this.defaultPreferences = [ ["Starfish", "Sea Otter", "Level 1", "Level 6", "Basics I"], ["Duck", "Salamander", "Level 2", "Level 7", "Basics II"], ["Sea Turtle", "Sunfish", "Level 3", "Level 8", "Strokes"], ["", "Crocodile", "Level 4", "Level 9", ""], ["Simple Set", "Whale", "Level 5", "Level 10", "Schoolboard"] ]; } componentDidMount() { var dynamicInstructorPreferences = document.getElementById("dynamicInstructorPreferences"); // Hide modal on click outside of modal. window.addEventListener("click", (e) => { if (e.target === ReactDOM.findDOMNode(this.modal)) { this.modal.setState({ "isDisplayed": false }); } else if (e.target.classList.contains("preferences") || dynamicInstructorPreferences.contains(e.target)) { this.modal.setState({ "isDisplayed": true }); } }); } /** * Remove an instructor's preferences from the state. */ deletePreference(instructorName) { if (instructorName in this.state.data) { delete this.state.data[instructorName] } } /** * Style the cell based on instructor preferences. */ getCellStyle(data, index) { var lesson = data[0]; var cellClass = "is-left "; var lessonType = lesson.props.data; var instructor = this.selectedInstructor; var preference = this.state.data[instructor]; var isSelected = preference.lessons.includes(lessonType); // Style non-selected cells. if (!isSelected && this.editButton) { if (this.editButton.state.mode === "edit") { cellClass += "remove-preference-"; } else { cellClass += "hide-preference-"; } cellClass += (index % 2) ? "even" : "odd"; } return cellClass; } /** * Update selection status of a preference cell and * update the state of the preferences. */ updatePreferenceCell(e) { if (this.editButton.state.mode === "default") { return; } var preferences; var lessonIndex; var lesson = e.target.innerHTML; var instructor = this.selectedInstructor; preferences = JSON.parse(JSON.stringify(this.state.data[instructor])); lessonIndex = preferences.lessons.indexOf(lesson); if (lessonIndex > -1) { preferences.lessons.splice(lessonIndex, 1); } else { preferences.lessons.push(lesson); } Object.assign(this.state.data[instructor], preferences); this.setState(this.state); } /** * Edit the lesson preference cells. */ getPreferenceButtons() { var preferences = JSON.parse(JSON.stringify(this.defaultPreferences)); for (let rowIndex = 0; rowIndex < preferences.length; rowIndex++) { let row = preferences[rowIndex]; for (let colIndex = 0; colIndex < row.length; colIndex++) { let lessonType = row[colIndex]; preferences[rowIndex][colIndex] = [ React.createElement(Anchor, { "data": lessonType, "handleClick": this.updatePreferenceCell.bind(this), "key": "key-anchor-" + (rowIndex * preferences.length + colIndex), "styleClass": "" } ) ]; } } return preferences; } /** * Displays preference modal. */ displayComponentState(instructorName) { this.selectedInstructor = instructorName; if (instructorName in this.state.data) { this.setState(this.state, () => this.modal.setState({ "header": [instructorName], "isDisplayed": true })); } else { // Fetch new data and set state for instructors without preferences. this.props.getPreferenceData() .then((res) => { this.setState(res, () => this.modal.setState({ "header": [instructorName], "isDisplayed": true })); }); } } /** * Sets the state of the Preferences table to * allow removal of cells. */ edit() { this.editButton.setState({ "handleClick": this.finishEditing.bind(this), "mode": "edit" }, () => this.setState(this.state)); } /** * Removes the 'remove-preference' and 'add-preference' * spans from the Preferences table . */ finishEditing() { this.editButton.setState({ "handleClick": this.edit.bind(this), "mode": "default" }, () => this.setState( this.state, () => this.props.callback(this.state, "instructorPreferences", true) )); } /** * Store a reference to the React object. */ setComponentReference(name, reference) { this[name] = reference } render() { return ( <Modal body={ [ <p key="key-modal-p-0"> The following table outlines { this.selectedInstructor }&#39;s level preferences. </p> ] } callback={ (ref) => this.setComponentReference("modal", ref) } footer={ [ React.createElement(EditButton, { "callback": (ref) => this.setComponentReference("editButton", ref), "handleClick": this.edit.bind(this), "key": "key-preferences-footer-0" }) ] } header={ [ this.selectedInstructor ] } tableData={ { "dataBody": this.getPreferenceButtons(), "dataHeader": [[ "Parent & Tot", "Pre-School", "Swim Kids", "Swim Kids", "Teens & Adults" ]], "styleCell": this.getCellStyle.bind(this), "styleRow": (index) => index % 2 ? "table-even" : "table-odd", "styleTable": "pure-table" } } /> );   } } InstructorPreferences.propTypes = { callback: PropTypes.func.isRequired, getPreferenceData: PropTypes.func.isRequired, initData: PropTypes.object.isRequired } export default InstructorPreferences;
app/component/quiz/SideMenuMoradores.js
vagnerpraia/ipeasurvey
import React, { Component } from 'react'; import { ScrollView, ToastAndroid } from 'react-native'; import { List, ListItem, Text } from 'native-base'; let admin; let quiz; export default class SideMenuMoradores extends Component { constructor(props) { super(props); admin = this.props.admin; quiz = this.props.quiz; } passQuestion(index, numeroQuestao){ let navigator = this.props.navigator; if(index < admin.indexPage){ admin.indexPage = index; navigator.replacePreviousAndPop({ name: 'morador', admin: admin, quiz: quiz }); }else if (index > admin.indexPage) { if(numeroQuestao <= admin.maxQuestion){ admin.indexPage = index; navigator.push({ name: 'morador', admin: admin, quiz: quiz, newQuiz: false }); }else{ ToastAndroid.showWithGravity('Responda a questão ' + admin.maxQuestion, ToastAndroid.SHORT, ToastAndroid.CENTER); } } } render() { return ( <ScrollView scrollsToTop={false}> <List> <ListItem key={1} onPress={() => {this.passQuestion(0, 1)}}> <Text>Questão 1</Text> </ListItem> <ListItem key={2} onPress={() => {this.passQuestion(1, 2)}}> <Text>Questão 2</Text> </ListItem> <ListItem key={3} onPress={() => {this.passQuestion(2, 3)}}> <Text>Questão 3</Text> </ListItem> <ListItem key={4} onPress={() => {this.passQuestion(3, 4)}}> <Text>Questão 4</Text> </ListItem> <ListItem key={5} onPress={() => {this.passQuestion(4, 5)}}> <Text>Questão 5</Text> </ListItem> <ListItem key={6} onPress={() => {this.passQuestion(5, 6)}}> <Text>Questão 6</Text> </ListItem> <ListItem key={7} onPress={() => {this.passQuestion(6, 7)}}> <Text>Questão 7</Text> </ListItem> <ListItem key={8} onPress={() => {this.passQuestion(7, 8)}}> <Text>Questão 8</Text> </ListItem> <ListItem key={9} onPress={() => {this.passQuestion(8, 9)}}> <Text>Questão 9</Text> </ListItem> <ListItem key={10} onPress={() => {this.passQuestion(9, 10)}}> <Text>Questão 10</Text> </ListItem> <ListItem key={11} onPress={() => {this.passQuestion(10, 11)}}> <Text>Questão 11</Text> </ListItem> <ListItem key={12} onPress={() => {this.passQuestion(11, 12)}}> <Text>Questão 12</Text> </ListItem> <ListItem key={13} onPress={() => {this.passQuestion(12, 13)}}> <Text>Questão 13</Text> </ListItem> <ListItem key={14} onPress={() => {this.passQuestion(13, 14)}}> <Text>Questão 14</Text> </ListItem> <ListItem key={15} onPress={() => {this.passQuestion(14, 15)}}> <Text>Questão 15</Text> </ListItem> <ListItem key={16} onPress={() => {this.passQuestion(15, 16)}}> <Text>Questão 16</Text> </ListItem> <ListItem key={17} onPress={() => {this.passQuestion(16, 17)}}> <Text>Questão 17</Text> </ListItem> <ListItem key={18} onPress={() => {this.passQuestion(17, 18)}}> <Text>Questão 18</Text> </ListItem> <ListItem key={19} onPress={() => {this.passQuestion(18, 19)}}> <Text>Questão 19</Text> </ListItem> <ListItem key={20} onPress={() => {this.passQuestion(19, 20)}}> <Text>Questão 20</Text> </ListItem> <ListItem key={21} onPress={() => {this.passQuestion(20, 21)}}> <Text>Questão 21</Text> </ListItem> <ListItem key={22} onPress={() => {this.passQuestion(21, 22)}}> <Text>Questão 22</Text> </ListItem> <ListItem key={23} onPress={() => {this.passQuestion(22, 23)}}> <Text>Questão 23</Text> </ListItem> </List> </ScrollView> ); } };
src/renderer/components/Frame/FrameLayouts.js
MovieCast/moviecast-desktop
import React, { Component } from 'react'; import { BrowserRouter } from 'react-router-dom'; import { withStyles } from '@material-ui/core/styles'; import NavLayout from '@/components/Layouts/NavLayout'; import FlexLayout from '@/components/Layouts/FlexLayout'; const styles = theme => ({ root: { display: 'flex', flexGrow: 1, width: "100%", position: 'relative' }, }); function getNavItemsFromChildren(children) { return React.Children.map(children, child => ({ text: child.props.title, path: child.props.path, icon: child.props.icon })); } class FrameLayouts extends Component { // Add Layouts here, only mainpage is displayed here render() { const { classes, children } = this.props; return ( <BrowserRouter> <div className={classes.root}> <NavLayout items={getNavItemsFromChildren(children)}> <FlexLayout> {children} </FlexLayout> </NavLayout> </div> </BrowserRouter> ); } } export default withStyles(styles)(FrameLayouts);
admin/client/App/components/Navigation/Mobile/index.js
giovanniRodighiero/cms
/** * The mobile navigation, displayed on screens < 768px */ import React from 'react'; import Transition from 'react-addons-css-transition-group'; import MobileSectionItem from './SectionItem'; const ESCAPE_KEY_CODE = 27; const MobileNavigation = React.createClass({ displayName: 'MobileNavigation', propTypes: { brand: React.PropTypes.string, currentListKey: React.PropTypes.string, currentSectionKey: React.PropTypes.string, sections: React.PropTypes.array.isRequired, signoutUrl: React.PropTypes.string, }, getInitialState () { return { barIsVisible: false, }; }, // Handle showing and hiding the menu based on the window size when // resizing componentDidMount () { this.handleResize(); window.addEventListener('resize', this.handleResize); }, componentWillUnmount () { window.removeEventListener('resize', this.handleResize); }, handleResize () { this.setState({ barIsVisible: window.innerWidth < 768, }); }, // Toggle the menu toggleMenu () { this[this.state.menuIsVisible ? 'hideMenu' : 'showMenu'](); }, // Show the menu showMenu () { this.setState({ menuIsVisible: true, }); // Make the body unscrollable, so you can only scroll in the menu document.body.style.overflow = 'hidden'; document.body.addEventListener('keyup', this.handleEscapeKey, false); }, // Hide the menu hideMenu () { this.setState({ menuIsVisible: false, }); // Make the body scrollable again document.body.style.overflow = null; document.body.removeEventListener('keyup', this.handleEscapeKey, false); }, // If the escape key was pressed, hide the menu handleEscapeKey (event) { if (event.which === ESCAPE_KEY_CODE) { this.hideMenu(); } }, renderNavigation () { if (!this.props.sections || !this.props.sections.length) return null; return this.props.sections.map((section) => { // Get the link and the classname const href = section.lists[0].external ? section.lists[0].path : `${Keystone.adminPath}/${section.lists[0].path}`; const className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'MobileNavigation__section is-active' : 'MobileNavigation__section'; // Render a SectionItem return ( <MobileSectionItem key={section.key} className={className} href={href} lists={section.lists} currentListKey={this.props.currentListKey} onClick={this.toggleMenu} > {section.label} </MobileSectionItem> ); }); }, // Render a blockout renderBlockout () { if (!this.state.menuIsVisible) return null; return <div className="MobileNavigation__blockout" onClick={this.toggleMenu} />; }, // Render the sidebar menu renderMenu () { if (!this.state.menuIsVisible) return null; return ( <nav className="MobileNavigation__menu"> <div className="MobileNavigation__sections"> {this.renderNavigation()} </div> </nav> ); }, render () { if (!this.state.barIsVisible) return null; return ( <div className="MobileNavigation"> <div className="MobileNavigation__bar"> <button type="button" onClick={this.toggleMenu} className="MobileNavigation__bar__button MobileNavigation__bar__button--menu" > <span className={'MobileNavigation__bar__icon octicon octicon-' + (this.state.menuIsVisible ? 'x' : 'three-bars')} /> </button> <span className="MobileNavigation__bar__label"> {this.props.brand} </span> <a href={this.props.signoutUrl} className="MobileNavigation__bar__button MobileNavigation__bar__button--signout" > <span className="MobileNavigation__bar__icon octicon octicon-sign-out" /> </a> </div> <div className="MobileNavigation__bar--placeholder" /> <Transition transitionName="MobileNavigation__menu" transitionEnterTimeout={260} transitionLeaveTimeout={200} > {this.renderMenu()} </Transition> <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={0} transitionLeaveTimeout={0} > {this.renderBlockout()} </Transition> </div> ); }, }); module.exports = MobileNavigation;
Realization/frontend/czechidm-core/src/content/scheduler/LongRunningTaskQueue.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; // import * as Basic from '../../components/basic'; import * as Advanced from '../../components/advanced'; import * as Utils from '../../utils'; import { LongRunningTaskItemManager, LongRunningTaskManager } from '../../redux'; import SearchParameters from '../../domain/SearchParameters'; import OperationStateEnum from '../../enums/OperationStateEnum'; import { SecurityManager } from '../../redux'; const UIKEY = 'long-running-task-queue-table'; const manager = new LongRunningTaskItemManager(); const longRunningTaskManager = new LongRunningTaskManager(); /** * Shows all items which were already added into the queue. Supports delete also. * * @author Marek Klement * @author Radek Tomiška */ class LongRunningTaskQueue extends Advanced.AbstractTableContent { constructor(props) { super(props); // this.state = { ...this.state, filterOpened: false }; } getManager() { return manager; } getNavigationKey() { return 'long-running-task-queue'; } getContentKey() { return 'content.scheduler.all-tasks'; } componentDidMount() { super.componentDidMount(); // const { entityId } = this.props.match.params; this.context.store.dispatch(longRunningTaskManager.fetchEntity(entityId)); } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } cancelFilter(event) { if (event) { event.preventDefault(); } this.refs.table.cancelFilter(this.refs.filterForm); } render() { const { entity, showLoading } = this.props; const { filterOpened, detail } = this.state; // if (showLoading) { return ( <Basic.Loading isStatic show /> ); } // if (!entity) { return null; } // return ( <Basic.Panel className="no-border last"> <Basic.Confirm ref="confirm-delete" level="danger"/> { !entity.scheduledTask ? <Basic.PanelBody style={{ padding: '15px 0' }}> <Basic.Alert level="info" text={ this.i18n('detail.scheduledTask.empty') } className="no-margin" /> </Basic.PanelBody> : <Advanced.Table ref="table" showRowSelection={ SecurityManager.hasAnyAuthority(['SCHEDULER_EXECUTE']) } uiKey={ UIKEY } manager={ manager } forceSearchParameters={ new SearchParameters().setFilter('scheduledTaskId', entity.scheduledTask) } rowClass={({rowIndex, data}) => { return Utils.Ui.getRowClass(data[rowIndex]); }} filter={ <Advanced.Filter onSubmit={this.useFilter.bind(this)}> <Basic.AbstractForm ref="filterForm"> <Basic.Row className="last"> <Basic.Col lg={ 4 }> <Advanced.Filter.EnumSelectBox ref="operationState" placeholder={this.i18n('entity.LongRunningTaskItem.result.state')} enum={OperationStateEnum}/> </Basic.Col> <Basic.Col lg={ 4 }> <Advanced.Filter.TextField ref="referencedEntityId" placeholder={this.i18n('entity.LongRunningTaskItem.referencedEntityId.placeholder')}/> </Basic.Col> <Basic.Col lg={ 4 } className="text-right"> <Advanced.Filter.FilterButtons cancelFilter={this.cancelFilter.bind(this)}/> </Basic.Col> </Basic.Row> </Basic.AbstractForm> </Advanced.Filter> } filterOpened={ filterOpened } actions={ SecurityManager.hasAnyAuthority(['SCHEDULER_EXECUTE']) ? [{ value: 'delete', niceLabel: this.i18n('action.delete.action'), action: this.onDelete.bind(this), disabled: false }] : null } _searchParameters={ this.getSearchParameters() }> <Advanced.Column className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={this.i18n('button.detail')} onClick={this.showDetail.bind(this, data[rowIndex])}/> ); } }/> <Advanced.Column property="operationResult.state" header={this.i18n('entity.LongRunningTaskItem.result.state')} width={75} sort cell={ ({ data, rowIndex }) => { return ( <Advanced.OperationResult value={ data[rowIndex].operationResult } detailLink={ () => this.showDetail(data[rowIndex]) }/> ); } } /> <Advanced.Column property="referencedEntityId" header={this.i18n('entity.LongRunningTaskItem.referencedEntityId')} cell={ ({ rowIndex, data, property }) => { if (!data[rowIndex]._embedded || !data[rowIndex]._embedded[property]) { return ( <Advanced.UuidInfo value={ data[rowIndex][property] } /> ); } // return ( <Advanced.EntityInfo entityType={ Utils.Ui.getSimpleJavaType(data[rowIndex].referencedDtoType) } entityIdentifier={ data[rowIndex][property] } entity={ data[rowIndex]._embedded[property] } face="popover" showEntityType={ false } showIcon/> ); } } sort face="text" /> <Advanced.Column property="referencedDtoType" header={this.i18n('entity.LongRunningTaskItem.referencedDtoType')} width={75} sort face="text" cell={ ({ rowIndex, data, property }) => { const javaType = data[rowIndex][property]; return ( <span title={ javaType }>{ Utils.Ui.getSimpleJavaType(javaType) }</span> ); } } /> <Advanced.Column property="created" header={this.i18n('entity.created')} width={75} sort face="datetime" /> </Advanced.Table> } <Basic.Modal show={ detail.show } onHide={ this.closeDetail.bind(this) } backdrop="static"> <Basic.Modal.Header text={ this.i18n('detail.header') }/> <Basic.Modal.Body> <Advanced.OperationResult value={ detail.entity ? detail.entity.operationResult : null } face="full"/> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={this.closeDetail.bind(this)}> {this.i18n('button.close')} </Basic.Button> </Basic.Modal.Footer> </Basic.Modal> </Basic.Panel> ); } } LongRunningTaskQueue.propTypes = { /** * Loaded LRT entity */ entity: PropTypes.object, /** * Entity is currently loaded from BE */ showLoading: PropTypes.bool }; LongRunningTaskQueue.defaultProps = { }; function select(state, component) { const { entityId } = component.match.params; return { entity: longRunningTaskManager.getEntity(state, entityId), showLoading: longRunningTaskManager.isShowLoading(state, null, entityId), _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY) }; } export default connect(select)(LongRunningTaskQueue);
src/pages/delight.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Delight' /> )
node_modules/react-router/es6/withRouter.js
lzm854676408/big-demo
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent) { var WithRouter = React.createClass({ displayName: 'WithRouter', contextTypes: { router: routerShape }, render: function render() { return React.createElement(WrappedComponent, _extends({}, this.props, { router: this.context.router })); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
app/app.js
akash6190/apollo-starter
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloProvider } from 'react-apollo'; import { withAsyncComponents } from 'react-async-component'; import { ConnectedRouter } from 'connected-react-router/immutable'; import FontFaceObserver from 'fontfaceobserver'; import { getStore, getHistory } from 'utils/store'; import { getClient } from 'utils/client'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` // import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-webpack-loader-syntax */ import '!file-loader?name=[name].[ext]!./images/favicon.ico'; import '!file-loader?name=[name].[ext]!./images/icon-72x72.png'; import '!file-loader?name=[name].[ext]!./images/icon-96x96.png'; import '!file-loader?name=[name].[ext]!./images/icon-120x120.png'; import '!file-loader?name=[name].[ext]!./images/icon-128x128.png'; import '!file-loader?name=[name].[ext]!./images/icon-144x144.png'; import '!file-loader?name=[name].[ext]!./images/icon-152x152.png'; import '!file-loader?name=[name].[ext]!./images/icon-167x167.png'; import '!file-loader?name=[name].[ext]!./images/icon-180x180.png'; import '!file-loader?name=[name].[ext]!./images/icon-192x192.png'; import '!file-loader?name=[name].[ext]!./images/icon-384x384.png'; import '!file-loader?name=[name].[ext]!./images/icon-512x512.png'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions /* eslint-enable import/no-webpack-loader-syntax */ // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import routes // import createRoutes from './routes'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); const iconsObserver = new FontFaceObserver('Material Icons', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body Promise.all([ openSansObserver.load(), iconsObserver.load(), ]).then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); const render = (messages) => { withAsyncComponents( <ApolloProvider store={getStore()} client={getClient()}> <LanguageProvider messages={messages}> <ConnectedRouter history={getHistory()} > <App /> </ConnectedRouter> </LanguageProvider> </ApolloProvider> ).then(({ appWithAsyncComponents }) => { ReactDOM.render(appWithAsyncComponents, document.getElementById('app')); }); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
app/Home.js
danbruder/cyclegram
import React from 'react' import api from './api' import { Redirect } from 'react-router-dom' import { Button, Checkbox, Form } from 'semantic-ui-react' export default class extends React.Component{ render() { return ( <div className="container"> Home </div> ) } }
app/components/ConnectDapp/VerifyOrSignMessage.js
CityOfZion/neon-wallet
// @flow import React from 'react' import classNames from 'classnames' import { isEmpty } from 'lodash-es' import { JsonRpcRequest } from '@json-rpc-tools/utils' import { useWalletConnect } from '../../context/WalletConnect/WalletConnectContext' import { ROUTES } from '../../core/constants' import CloseButton from '../CloseButton' import FullHeightPanel from '../Panel/FullHeightPanel' import WallletConnect from '../../assets/icons/wallet_connect.svg' import styles from '../../containers/ConnectDapp/styles.scss' import CheckMarkIcon from '../../assets/icons/confirm-circle.svg' import DialogueBox from '../DialogueBox' import WarningIcon from '../../assets/icons/warning.svg' import Confirm from '../../assets/icons/confirm_connection.svg' import Deny from '../../assets/icons/deny_connection.svg' const VerifyOrSignMessage = ({ request, peer, isHardwareLogin, resetState, history, showSuccessNotification, setLoading, loading, isSignMessage, }: { request: JsonRpcRequest, peer: any, isHardwareLogin: boolean, resetState: () => any, history: any, showSuccessNotification: ({ message: string }) => any, setLoading: boolean => any, loading: boolean, isSignMessage: boolean, }) => { const walletConnectCtx = useWalletConnect() const returnRequestParam = param => { if (typeof param === 'string') return param return '' } return ( <FullHeightPanel headerText="Wallet Connect" renderCloseButton={() => ( <CloseButton routeTo={ROUTES.DASHBOARD} onClick={() => { walletConnectCtx.rejectRequest(request) resetState() history.push(ROUTES.DASHBOARD) }} /> )} renderHeaderIcon={() => ( <div className={styles.walletConnectIcon}> <WallletConnect /> </div> )} renderInstructions={false} > <div className={classNames([ styles.approveConnectionContainer, styles.approveRequestContainer, ])} > <img src={peer && peer.metadata.icons[0]} /> <h3> <h3>{peer && peer.metadata.name} wants you to verify a message</h3> </h3> {isHardwareLogin && ( <DialogueBox icon={ <WarningIcon className={styles.warningIcon} height={60} width={60} /> } renderText={() => ( <div> You can view the message below however, the N3 ledger app does not currently support message signing/verification. </div> )} className={styles.warningDialogue} /> )} {!isSignMessage && ( <div className={styles.connectionDetails}> <div className={styles.details} style={{ margin: '12px 0', padding: '12px' }} > <div> {!isEmpty(request.request.params) && Object.keys(request.request.params).map(param => ( <div key={param}> <div className={classNames([ styles.detailsLabel, styles.detailRow, ])} > <label>{param}</label> </div> <div className={styles.methodParameter} style={{ wordBreak: 'break-all', fontSize: 12, }} > {returnRequestParam(request.request.params[param])} </div> </div> ))} </div> </div> </div> )} {isSignMessage && ( <div className={styles.connectionDetails}> <div className={styles.details} style={{ margin: '12px 0', padding: '12px' }} > <div className={styles.detailsLabel} style={{ marginBottom: '6px' }} > <label>Message</label> </div> <div>{request.request.params}</div> </div> </div> )} {!isHardwareLogin && ( <div className={styles.confirmation}> Please confirm you would like to proceed <div> <Confirm onClick={async () => { if (!loading) { setLoading(true) await walletConnectCtx.approveRequest(request) setLoading(false) } }} /> <Deny onClick={() => { if (!loading) { showSuccessNotification({ message: `You have denied request from ${ peer ? peer.metadata.name : 'unknown dApp' }.`, }) walletConnectCtx.rejectRequest(request) resetState() history.push(ROUTES.DASHBOARD) } }} /> </div> </div> )} </div> </FullHeightPanel> ) } export default VerifyOrSignMessage
frontend/component/Profile.js
auronzhong/pratice-node-project
/** * Created by zhongwei on 16/7/23. */ import React from 'react'; import jQuery from 'jquery'; import {loginUser, updateProfile} from '../lib/client'; import {redirectURL} from '../lib/utils'; export default class Profile extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { loginUser() .then(user => this.setState(user)) .catch(err => console.error(err)); } handleChange(name, e) { this.setState({[name]: e.target.value}); } handleSave(e) { const $btn = jQuery(e.target); $btn.button('loading'); updateProfile(this.state.email, this.state.nickname, this.state.about, this.state.githubUsername) .then(ret => { $btn.button('reset'); alert('修改成功!'); }) .catch(err => { $btn.button('reset'); alert(err); }); } handleRemoveGithub(e) { const $btn = jQuery(e.target); $btn.button('loading'); updateProfile(this.state.email, this.state.nickname, this.state.about, '') .then(ret => { $btn.button('reset'); alert('解除绑定成功!'); }) .catch(err => { $btn.button('reset'); alert(err); }); } render() { if (!this.state._id) { return ( <p>正在加载...</p> ) } return ( <div style={{width: 400, margin: 'auto'}}> <div className="panel panel-primary"> <div className="panel-heading">{this.state.name} 的个人设置</div> <div className="panel-body"> <form> <div className="form-group"> <label htmlFor="ipt-email">邮箱</label> <input type="email" className="form-control" id="ipt-email" onChange={this.handleChange.bind(this, 'email')} placeholder="" value={this.state.email}/> </div> <div className="form-group"> <label htmlFor="ipt-nickname">昵称</label> <input type="text" className="form-control" id="ipt-nickname" onChange={this.handleChange.bind(this, 'nickname')} placeholder="" value={this.state.nickname}/> </div> <div className="form-group"> <label htmlFor="ipt-githubUsername">Github账号</label> <input type="text" className="form-control" id="ipt-githubUsername" onChange={this.handleChange.bind(this, 'githubUsername')} placeholder="" value={this.state.githubUsername}/> </div> <div className="form-group"> <label htmlFor="ipt-about">个人介绍</label> <textarea className="form-control" id="ipt-about" onChange={this.handleChange.bind(this, 'about')} placeholder="">{this.state.about}</textarea> </div> <button type="button" className="btn btn-primary" onClick={this.handleSave.bind(this)}>保存 </button> <button type="button" className="btn btn-primary" onClick={this.handleRemoveGithub.bind(this)}>解除GitHub绑定 </button> </form> </div> </div> </div> ) } }
src/components/Header/Header.js
treeforever/voice-recognition-photo-gallary
import React from 'react' // import { IndexLink, Link } from 'react-router' import { Router, Route, Link, browserHistory } from 'react-router' import OwlImage from '../../routes/Home/assets/owl.jpg' import HomeView from '../../routes/Home' import TagView from '../../routes/Tag' import './Header.scss' export const Header = () => ( <div> <span id='app-title'>Owl my photos</span> <img alt='This is a owl!' className='owl' src={OwlImage} width='200px' height='200px' /> <Router history={browserHistory}> <Route path="/" component={HomeView}>Home <Route path="about" component={TagView}/> </Route> </Router> </div> ) export default Header // <IndexLink to='/' activeClassName='route--active'> // Home // </IndexLink> // {' · '} // <Link to='/tag' activeClassName='route--active'> // Tag // </Link>
src/static/containers/NotFound/index.js
spiskommg/mm-v2
import React from 'react'; export default class NotFoundView extends React.Component { componentWillMount() { console.log(this.props.location.pathname); } render() { return ( <div> <h1>NOT FOUND</h1> </div> ); } }
app/components/List/index.js
Ennovar/clock_it
import React from 'react'; import Ul from './Ul'; import Wrapper from './Wrapper'; function List(props) { const ComponentToRender = props.component; let content = (<div></div>); // If we have items, render them if (props.items) { content = props.items.map((item, index) => ( <ComponentToRender key={`item-${index}`} item={item} /> )); } else { // Otherwise render a single component content = (<ComponentToRender />); } return ( <Wrapper> <Ul> {content} </Ul> </Wrapper> ); } List.propTypes = { component: React.PropTypes.func.isRequired, items: React.PropTypes.array, }; export default List;
src/client/athrun/apps/demo/screens/home/components/ControlPanel.js
cnfi/laboratory
import React, { Component } from 'react'; import shallowCompare from 'react-addons-shallow-compare' import { Input } from 'antd'; import TestBox from './TestBox' class ControlPanel extends React.Component{ shouldComponentUpdate(nextProps) { return shallowCompare(this.props.home.text, nextProps.home.text); } getChildContext() { return { testContextType: ()=>console.log('ContextType test success in ControlPanel!') } } render(){ return ( <div> <Input style={{width: 400}} size="large" value={this.props.home.text} onChange={this.handleChange.bind(this)} /> <br /><br /> <TestBox /> </div> ) } handleChange(e){ this.props.changeTitle(e.target.value) } } ControlPanel.childContextTypes = { testContextType: React.PropTypes.func }; export default ControlPanel;
packages/@vega/components/src/views/CommentBlockEditor/CommentBlockEditor.js
VegaPublish/vega-studio
import PropTypes from 'prop-types' import React from 'react' import {BlockEditor} from 'part:@lyra/form-builder' export default class CommentBlockEditor extends React.Component { static propTypes = { type: PropTypes.shape({ title: PropTypes.string }).isRequired, level: PropTypes.number, value: PropTypes.array, markers: PropTypes.array, onChange: PropTypes.func.isRequired } handlePaste = input => { const {event, path} = input const jsonData = event.clipboardData.getData('application/json') if (jsonData) { const data = JSON.parse(jsonData) return {insert: data, path} } return undefined } render() { return ( <div> <BlockEditor {...this.props} onPaste={this.handlePaste} /> </div> ) } }
src/js/components/icons/base/BottomCorner.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-bottom-corner`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'bottom-corner'); 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}><polyline fill="none" stroke="#000" strokeWidth="2" points="8 20 20 20 20 8"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'BottomCorner'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
website/src/components/title.js
spacy-io/spaCy
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import Button from './button' import Tag from './tag' import { OptionalLink } from './link' import { InlineCode } from './code' import { H1, Label, InlineList, Help } from './typography' import Icon from './icon' import classes from '../styles/title.module.sass' const MetaItem = ({ label, url, children, help }) => ( <span> <Label className={classes.label}>{label}:</Label> <OptionalLink to={url}>{children}</OptionalLink> {help && ( <> {' '} <Help>{help}</Help> </> )} </span> ) export default function Title({ id, title, tag, version, teaser, source, image, apiDetails, children, ...props }) { const hasApiDetails = Object.values(apiDetails || {}).some(v => v) const metaIconProps = { className: classes.metaIcon, width: 18 } return ( <header className={classes.root}> {(image || source) && ( <div className={classes.corner}> {source && ( <Button to={source} icon="code"> Source </Button> )} {image && ( <div className={classes.image}> <img src={image} width={100} height={100} alt="" /> </div> )} </div> )} <H1 className={classes.h1} id={id} {...props}> {title} </H1> {(tag || version) && ( <div className={classes.tags}> {tag && <Tag spaced>{tag}</Tag>} {version && ( <Tag variant="new" spaced> {version} </Tag> )} </div> )} {hasApiDetails && ( <InlineList Component="div" className={classes.teaser}> {apiDetails.stringName && ( <MetaItem label="String name" //help="String name of the component to use with nlp.add_pipe" > <InlineCode>{apiDetails.stringName}</InlineCode> </MetaItem> )} {apiDetails.baseClass && ( <MetaItem label="Base class" url={apiDetails.baseClass.slug}> <InlineCode>{apiDetails.baseClass.title}</InlineCode> </MetaItem> )} {apiDetails.trainable != null && ( <MetaItem label="Trainable"> <span aria-label={apiDetails.trainable ? 'yes' : 'no'}> {apiDetails.trainable ? ( <Icon name="yes" variant="success" {...metaIconProps} /> ) : ( <Icon name="no" {...metaIconProps} /> )} </span> </MetaItem> )} </InlineList> )} {teaser && <div className={classNames('heading-teaser', classes.teaser)}>{teaser}</div>} {children} </header> ) } Title.propTypes = { title: PropTypes.string, tag: PropTypes.string, teaser: PropTypes.node, source: PropTypes.string, image: PropTypes.string, children: PropTypes.node, }
src/widgets/arrow_nav2/index.js
HelloQingGuo/HelloQingGuo.github.io
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Icon } from 'antd'; import { links as navItems } from '../constants/links'; import { navigate } from '../../actions/action_ui'; import './index.css'; const getIdx = (direction, curIdx, totalCount) => { if (curIdx === 0 && direction === -1) { return totalCount - 1; } if (curIdx === totalCount - 1 && direction === 1) { return 0; } return curIdx + direction; }; class NavHeader extends Component { constructor(props) { super(props); this.handleClickLeft = this.handleClickLeft.bind(this); this.handleClickRight = this.handleClickRight.bind(this); } handleClickLeft() { this.props.navigate(-1, this.props.curNavHeaderIdx, navItems); } handleClickRight() { this.props.navigate(1, this.props.curNavHeaderIdx, navItems); } render() { const { curNavHeaderIdx } = this.props; return ( <div className="navheader"> <div className="counter"> {curNavHeaderIdx + 1} of {navItems.length} </div> <div className="arrows"> <Link to={navItems[getIdx(-1, curNavHeaderIdx, navItems.length)].link}> <Icon type="arrow-left" className="left-arrow" onClick={this.handleClickLeft} /> </Link> <Link to="/dashboard/projects"> <Icon type="close" className="middle" /> </Link> <Link to={navItems[getIdx(1, curNavHeaderIdx, navItems.length)].link}> <Icon type="arrow-right" className="right-arrow" onClick={this.handleClickRight} /> </Link> </div> </div> ); } } function mapStateToProps(state) { return { curNavHeaderIdx: state.ui.curNavHeaderIdx, }; } NavHeader.propTypes = { navigate: PropTypes.func.isRequired, curNavHeaderIdx: PropTypes.number.isRequired, }; export default connect(mapStateToProps, { navigate })(NavHeader);
src/svg-icons/navigation/arrow-drop-down.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDown = (props) => ( <SvgIcon {...props}> <path d="M7 10l5 5 5-5z"/> </SvgIcon> ); NavigationArrowDropDown = pure(NavigationArrowDropDown); NavigationArrowDropDown.displayName = 'NavigationArrowDropDown'; NavigationArrowDropDown.muiName = 'SvgIcon'; export default NavigationArrowDropDown;
components/Form/Checkbox/Checkbox.js
rdjpalmer/bloom
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import cx from 'classnames'; import uniqueId from 'lodash/fp/uniqueId'; import css from './Checkbox.css'; import noop from '../../../utils/noop'; import Icon from '../../Icon/Icon'; import ScreenReadable from '../../ScreenReadable/ScreenReadable'; import LeftRight from '../../LeftRight/LeftRight'; export default class Checkbox extends Component { static propTypes = { name: PropTypes.string.isRequired, onFocus: PropTypes.func, onBlur: PropTypes.func, onChange: PropTypes.func, children: PropTypes.node, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, checked: PropTypes.bool, className: PropTypes.string, label: PropTypes.node, }; static defaultProps = { onChange: noop, onFocus: noop, onBlur: noop, }; constructor(props) { super(props); this.id = uniqueId('radio'); } state = { hasFocus: false, } focus = () => { this.input.focus(); this.handleFocus(); } blur = () => { this.input.blur(); this.handleBlur(); } handleFocus = () => { const { onFocus } = this.props; this.setState({ hasFocus: true }, onFocus); } handleBlur = () => { const { onBlur } = this.props; this.setState({ hasFocus: false }, onBlur); } handleChange = (e) => { const { name, value, onChange } = this.props; onChange(e, name, value); } render() { const { children, value, checked, name, label, className, ...rest, } = this.props; return ( <span className={ cx(css.root, className) }> <input { ...rest } id={ this.id } type="checkbox" name={ name } value={ value } checked={ checked } onChange={ this.handleChange } ref={ (c) => { this.input = c; } } onFocus={ this.handleFocus } onBlur={ this.handleBlur } /> <label htmlFor={ this.id }> { children ? ( <div><ScreenReadable>{ value }</ScreenReadable>{ children }</div> ) : ( <div> <ScreenReadable>{ value }</ScreenReadable> <LeftRight leftChildren={ ( <span className={ css.checkbox }> <Icon className={ css.icon } name="tick" /> </span> ) } rightChildren={ ( <span className={ css.label }>{ label }</span> ) } primarySide="right" rightClassName={ css.labelContainer } /> </div> ) } </label> </span> ); } }
src/nav-team.js
FederationOfFathers/ui
import React, { Component } from 'react'; class TeamNav extends Component { constructor(props) { super(props) this.state = { subNavSelected: false, } } subNavClick = () => { if ( this.state.subNavSelected === true ) { this.setState({subNavSelected: false}) } else { this.setState({subNavSelected: true}) } } click = () => { if ( this.props.state.vars.event !== "host" ) { this.props.state.hasher.set({event: "host"}) } else { this.props.state.hasher.set({event: null}) } } joinClick = () => { var raid = this.props.state.raids.raids[this.props.state.vars.chan][this.props.state.vars.raid] var body = new URLSearchParams() body.set('channel', this.props.state.vars.chan) body.set('raid', raid.name) this.props.state.api.team.join(body) } viewingRaid = () => { if ( this.state.subNavSelected === true ) { return this.viewingSubNav() } var raid = this.props.state.raids.raids[this.props.state.vars.chan][this.props.state.vars.raid] if ( typeof raid === "undefined" ) { // raid no longer exists... return this.canHostFromHere() } var inRaid = raid.members.indexOf(this.props.state.user.name) var rval = [] var text = "" switch( inRaid ) { case -1: text = "Join This Event" if ( raid.need > 0 && raid.members.length >= raid.need ) { text = "It's full, but I'll wait in line" } rval.push(( <li key="user" className="nav-item px-1 my-1"> <button onClick={this.joinClick} type="button" style={{fontSize: "0.7em"}} className="btn btn-primary w-100">{text}</button> </li> )) break; default: text = "Hold Another Spot" if ( raid.need > 0 && raid.members.length >= raid.need ) { text = "It's full, but I'll hold a spot in line" } rval.push(( <li key="join" className="nav-item px-1 my-1"> <button style={{fontSize: "0.7em"}} onClick={this.joinClick} className="btn btn-primary w-100">{text}</button> </li> )); break; } return ( <ul className="nav nav-pills nav-fill"> {rval} </ul> ) } addingRaid = () => { return ( <ul className="nav nav-pills nav-fill"> <li className="nav-item px-1 my-1"> <button onClick={this.click} style={{fontSize: "0.7em"}} className="btn btn-danger w-100">Cancel</button> </li> </ul> ) } canHostFromHere = () => { return ( <ul className="nav nav-pills nav-fill"> <li className="nav-item px-1 my-1"> <button onClick={this.click} style={{fontSize: "0.7em"}} className="btn btn-success w-100">Host an Event</button> </li> </ul> ) } render = () => { if ( this.props.state.vars.main !== "events" ) { return null } if ( this.props.state.vars.event === "host" ) { return this.addingRaid() } if ( typeof this.props.state.vars.event !== 'undefined' && this.props.state.vars.event !== null ) { return this.viewingRaid() } return this.canHostFromHere() } } export default TeamNav
docs/app/Examples/elements/List/Variations/ListExampleInverted.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { List, Segment } from 'semantic-ui-react' const ListExampleInverted = () => ( <Segment inverted> <List divided inverted relaxed> <List.Item> <List.Content> <List.Header>Snickerdoodle</List.Header> An excellent companion </List.Content> </List.Item> <List.Item> <List.Content> <List.Header>Poodle</List.Header> A poodle, its pretty basic </List.Content> </List.Item> <List.Item> <List.Content> <List.Header>Paulo</List.Header> He's also a dog </List.Content> </List.Item> </List> </Segment> ) export default ListExampleInverted
src/js/pages/Proposals/Experience/FeaturesPage.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import translate from '../../../i18n/Translate'; import TopNavBar from '../../../components/TopNavBar/TopNavBar.js'; import '../../../../scss/pages/proposals/experience/features.scss'; import StepsBar from "../../../components/ui/StepsBar/StepsBar"; import connectToStores from "../../../utils/connectToStores"; import * as ProposalActionCreators from "../../../actions/ProposalActionCreators"; import TagSuggestionsStore from "../../../stores/TagSuggestionsStore"; import RoundedIcon from "../../../components/ui/RoundedIcon/RoundedIcon"; import FrameCollapsible from "../../../components/ui/FrameCollapsible/FrameCollapsible"; import ThreadStore from "../../../stores/ThreadStore"; import FilterStore from "../../../stores/FilterStore"; import * as ThreadActionCreators from "../../../actions/ThreadActionCreators"; import ChoiceFilter from "../../../components/_threads/filters/ChoiceFilter"; import LocationFilter from "../../../components/Threads/Filters/LocationFilter"; import IntegerRangeFilter from "../../../components/Threads/Filters/IntegerRangeFilter"; import IntegerFilter from "../../../components/Threads/Filters/IntegerFilter"; import MultipleChoicesFilter from "../../../components/Threads/Filters/MultipleChoicesFilter"; import DoubleMultipleChoicesFilter from "../../../components/_threads/filters/DoubleMultipleChoicesFilter"; import ChoiceAndMultipleChoicesFilter from "../../../components/Threads/Filters/ChoiceAndMultipleChoicesFilter"; import TagFilter from "../../../components/Threads/Filters/TagFilter"; import TagsAndMultipleChoicesFilter from "../../../components/Threads/Filters/TagsAndMultipleChoicesFilter"; import AuthenticatedComponent from "../../../components/AuthenticatedComponent"; function parseThreadId(thread) { return thread && thread.hasOwnProperty('id') ? thread.id : null; } /** * Requests data from server for current props. */ function requestData(props) { const userId = props.user.id; ThreadActionCreators.requestFilters(userId); ThreadActionCreators.requestThreads(userId); } function getDisplayedThread(props) { if (props.params.groupId) { return ThreadStore.getByGroup(props.params.groupId) || {}; } return ThreadStore.getMainDiscoverThread(); } function getState(props) { const mainThread = getDisplayedThread(props); const filters = FilterStore.filters; const tags = TagSuggestionsStore.tags; const threadId = parseThreadId(mainThread); const thread = ThreadStore.get(threadId); const categories = ThreadStore.getCategories(); const errors = ThreadStore.getErrors(); const isLoadingFilters = FilterStore.isLoading(); return { tags, filters, thread, categories, errors, isLoadingFilters }; } @AuthenticatedComponent @translate('ProposalsLeisureFeaturesPage') @connectToStores([FilterStore, TagSuggestionsStore, ThreadStore], getState) export default class FeaturesPage extends Component { static propTypes = { threadId : PropTypes.string, // Injected by @AuthenticatedComponent user : PropTypes.object.isRequired, // Injected by @translate: strings : PropTypes.object, // Injected by @connectToStores: filters : PropTypes.object, tags : PropTypes.array, thread : PropTypes.object.isRequired, categories : PropTypes.array, errors : PropTypes.string, canContinue : PropTypes.bool, }; static contextTypes = { router: PropTypes.object.isRequired }; constructor(props) { super(props); this.topNavBarLeftLinkClick = this.topNavBarLeftLinkClick.bind(this); this.topNavBarRightLinkClick = this.topNavBarRightLinkClick.bind(this); this.handleClickFilter = this.handleClickFilter.bind(this); this.handleChangeFilter = this.handleChangeFilter.bind(this); this.handleChangeFilterAndUnSelect = this.handleChangeFilterAndUnSelect.bind(this); this.handleClickRemoveFilter = this.handleClickRemoveFilter.bind(this); this.handleErrorFilter = this.handleErrorFilter.bind(this); this.renderField = this.renderField.bind(this); this.handleStepsBarClick = this.handleStepsBarClick.bind(this); const data = props.thread && props.thread.filters && props.thread.filters.userFilters ? props.thread.filters.userFilters : {}; this.state = { data: data, } } componentDidMount() { requestData(this.props); } componentDidUpdate() { const {thread} = this.props; const {data} = this.state; if (Object.keys(data).length === 0 && thread && thread.filters && thread.filters.userFilters && Object.keys(thread.filters.userFilters).length > 0) { this.setState({data: thread.filters.userFilters}) } } topNavBarLeftLinkClick() { this.context.router.push('/proposals-experience-availability'); } topNavBarRightLinkClick() { ProposalActionCreators.cleanCreatingProposal(); this.context.router.push('/proposals'); } handleClickFilter(field, filter) { this.save(field, filter); } handleChangeFilter(field, filter) { this.save(field, filter); } handleChangeFilterAndUnSelect(field, filter) { this.save(field, filter); } handleClickRemoveFilter(field) { // const threadId = this.props.thread.id; let userFilters = Object.assign({}, this.props.thread.filters.userFilters); if (userFilters[field]) { userFilters[field] = null; } // let data = { // name : this.props.thread.name, // filters : {userFilters: userFilters}, // category: 'ThreadUsers' // }; // ThreadActionCreators.updateThread(threadId, data) // .then(() => { // this.setState({updated: true}); // }, () => { // // TODO: Handle error // }); this.setState({data: userFilters}); } handleErrorFilter() { } save(field, filter) { // const threadId = this.props.thread.id; const filters = {userFilters: {...this.props.thread.filters.userFilters, ...{[field]: filter}}}; // let data = { // name : this.props.thread.name, // filters : filters, // category: 'ThreadUsers' // }; // ThreadActionCreators.updateThread(threadId, data) // .then(() => { // this.setState({updated: true}); // }, () => { // // TODO: Handle error // }); this.setState({data: filters.userFilters}); } hideRenderCategory(categories) { const categoriesToHide = ["leisureMoney", "shows", "plans", "restaurants"]; if (categories) { categories.forEach(function (category, index) { if (JSON.stringify(category.fields) === JSON.stringify(categoriesToHide)) { categories.splice(index, 1); } }); } } renderField(field) { const {tags, filters} = this.props; const {data} = this.state; if (filters && filters.userFilters && filters.userFilters[field]) { const filter = filters.userFilters[field]; const filterData = data[field] ? data[field] : null; switch (filter.type) { case 'location_distance': return this.renderLocationFilter(field, filter, filterData); break; case 'integer_range': return this.renderIntegerRangeFilter(field, filter, filterData); break; case 'birthday_range': return this.renderIntegerRangeFilter(field, filter, filterData); break; case 'integer': return this.renderIntegerFilter(field, filter, filterData); break; case 'multiple_choices': return this.renderMultipleChoicesFilter(field, filter, filterData); break; case 'double_multiple_choices': return this.renderDoubleMultipleChoicesFilter(field, filter, filterData); break; case 'choice_and_multiple_choices': return this.renderChoiceAndMultipleChoicesFilter(field, filter, filterData); break; case 'tags_and_multiple_choices': return this.renderTagsAndMultipleChoicesFilter(field, filter, filterData, tags); break; case 'tags': return this.renderTagFilter(field, filter, filterData, tags); break; } } } renderChoiceFilter(field, filter, data) { return ( <ChoiceFilter filter={filter} filterKey={field} data={data} selected={true} handleChangeFilter={this.handleChangeFilterAndUnSelect} cantRemove={key === 'order'} /> ); } renderLocationFilter(field, filter, data) { return ( <LocationFilter filterKey={field} filter={filter} data={data} selected={true} handleClickRemoveFilter={this.handleClickRemoveFilter} handleChangeFilter={this.handleChangeFilter} handleClickFilter={this.handleClickFilter} color={'#7bd47e'} /> ); } renderIntegerRangeFilter(field, filter, data) { return ( <IntegerRangeFilter filterKey={field} filter={filter} data={data} handleChangeFilter={this.handleChangeFilter} color={'#7bd47e'} /> ) } renderIntegerFilter(field, filter, data) { return ( <IntegerFilter filterKey={field} filter={filter} data={data} handleChangeFilter={this.handleChangeFilterAndUnSelect} /> ) } renderMultipleChoicesFilter(field, filter, data) { return ( <MultipleChoicesFilter filterKey={field} filter={filter} data={data} handleChangeFilter={this.handleChangeFilter} color={'green'} /> ); } renderDoubleMultipleChoicesFilter(field, filter, data) { return ( <DoubleMultipleChoicesFilter filterKey={field} filter={filter} data={data} selected={true} handleClickRemoveFilter={this.handleClickRemoveFilter} handleChangeFilter={this.handleChangeFilter} handleClickFilter={this.handleClickFilter} color={'green'} /> ); } renderChoiceAndMultipleChoicesFilter(field, filter, data) { return ( <ChoiceAndMultipleChoicesFilter filterKey={field} filter={filter} data={data} handleChangeFilter={this.handleChangeFilter} color={'green'} /> ); } renderTagFilter(field, filter, data, tags) { return ( <TagFilter filterKey={field} filter={filter} data={data} selected={true} handleClickRemoveFilter={this.handleClickRemoveFilter} handleChangeFilter={this.handleChangeFilterAndUnSelect} handleClickFilter={this.handleClickFilter} tags={tags} color={'green'} /> ); } renderTagsAndMultipleChoicesFilter(field, filter, data, tags) { return ( <TagsAndMultipleChoicesFilter filterKey={field} filter={filter} data={data} selected={true} handleClickRemoveFilter={this.handleClickRemoveFilter} handleChangeFilter={this.handleChangeFilter} handleClickFilter={this.handleClickFilter} tags={tags} color={'green'} /> ); } handleStepsBarClick() { const proposal = { filters: { userFilters: this.state.data } }; ProposalActionCreators.mergeCreatingProposal(proposal); this.context.router.push('/proposals-experience-preview'); } render() { const {user, tags, thread, categories, strings, isLoadingFilters} = this.props; const {updated} = this.state; const canContinue = !isLoadingFilters; this.hideRenderCategory(categories); return ( <div className="views"> <div className="view view-main proposals-experience-features-view"> <TopNavBar background={'#FBFCFD'} iconLeft={'arrow-left'} firstIconRight={'x'} textCenter={strings.publishProposal} textSize={'small'} onLeftLinkClickHandler={this.topNavBarLeftLinkClick} onRightLinkClickHandler={this.topNavBarRightLinkClick}/> <div className="proposals-experience-features-wrapper"> <h2>{strings.title}</h2> <div className={'warning-container'}> <div className={'warning-icon-container'}> <RoundedIcon color={'#818FA1'} background={'#FBFCFD'} icon={'eye'} size={'small'}/> </div> <div>{strings.filterWarning}</div> </div> {categories ? categories.map((category, index) => <FrameCollapsible key={index} title={category.label}> {category.fields.map((field, index) => <div key={index} className="filter"> {/*<div className="remove">*/} {/*<RoundedIcon*/} {/*icon={'delete'}*/} {/*size={'small'}*/} {/*fontSize={'16px'}*/} {/*disabled={field === 'group' && thread.groupId != null}*/} {/*onClickHandler={this.handleClickRemoveFilter.bind(this, field)}/>*/} {/*</div>*/} {this.renderField(field)} </div> )} </FrameCollapsible>) : null } </div>availability, interfaceLanguage, </div> <StepsBar color={'green'} totalSteps={5} currentStep={4} continueText={strings.stepsBarContinueText} cantContinueText={strings.stepsBarCantContinueText} canContinue={canContinue} onClickHandler={this.handleStepsBarClick}/> </div> ); } } FeaturesPage.defaultProps = { strings: { publishProposal : 'Publish proposal', title : 'Are you looking for people with specific features?', filterWarning : 'This filters only be visible for you and we need to filter users', stepsBarContinueText : 'Continue', stepsBarCantContinueText : 'You cannot continue', } };
threeforce/node_modules/react-bootstrap/es/NavItem.js
wolfiex/VisACC
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: React.PropTypes.bool, disabled: React.PropTypes.bool, role: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var disabled = _props.disabled; var onClick = _props.onClick; var className = _props.className; var style = _props.style; var props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
src/index.js
cleancodegame/clean-code-game
import React from 'react' import ReactDOM from 'react-dom' import AppContainer from './view/App' import Scoreboard from './view/Scoreboard' import { Provider } from 'react-redux' import { createStore, applyMiddleware, combineReducers, compose } from 'redux' import createSagaMiddleware from 'redux-saga' import authReducer from './core/auth/reducers' import gameReducer from './core/game/reducers' import appReducer from './core/app/reducers' import scoreboardReducer from './core/scoreboard/reducers' import './core/database' import saga from './core/sagas' import initAuth from './core/auth/init' import initGame from './core/app/init' import { Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore, routerReducer } from 'react-router-redux' const initialState = { app: { state: 'HOME' }, scoreboard: { scores: [], userScores: [] }, } const logger = store => next => action => { console.group(action.type) console.info('dispatching', action) let result = next(action) console.log('next state', store.getState()) console.groupEnd(action.type) return result } const sagaMiddleware = createSagaMiddleware() const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore( combineReducers({ auth: authReducer, game: gameReducer, app: appReducer, scoreboard: scoreboardReducer, routing: routerReducer, }), initialState, composeEnhancers(applyMiddleware(sagaMiddleware, logger)) ) const history = syncHistoryWithStore(browserHistory, store) sagaMiddleware.run(saga) function render() { ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/" component={AppContainer} /> <Route path="/scoreboard" component={Scoreboard} /> </Router> </Provider>, document.getElementById("root") ) } initAuth(store.dispatch) .then(initGame) .then(() => render()) .catch(error => console.error(error))
app/react-icons/fa/search-plus.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaSearchPlus extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m24.4 17.9v1.4q0 0.3-0.3 0.5t-0.5 0.2h-5v5q0 0.3-0.2 0.5t-0.5 0.2h-1.4q-0.3 0-0.5-0.2t-0.2-0.5v-5h-5q-0.3 0-0.5-0.2t-0.2-0.5v-1.4q0-0.3 0.2-0.5t0.5-0.3h5v-5q0-0.2 0.2-0.5t0.5-0.2h1.4q0.3 0 0.5 0.2t0.2 0.5v5h5q0.3 0 0.5 0.3t0.3 0.5z m2.8 0.7q0-4.2-2.9-7.1t-7.1-2.9-7 2.9-3 7.1 2.9 7 7.1 3 7.1-3 2.9-7z m11.4 18.5q0 1.2-0.8 2.1t-2 0.8q-1.2 0-2-0.8l-7.7-7.7q-4 2.8-8.9 2.8-3.2 0-6.1-1.3t-5-3.3-3.4-5-1.2-6.1 1.2-6.1 3.4-5.1 5-3.3 6.1-1.2 6.1 1.2 5 3.3 3.4 5.1 1.2 6.1q0 4.9-2.7 8.9l7.6 7.6q0.8 0.9 0.8 2z"/></g> </IconBase> ); } }
lib/codemod/src/transforms/__testfixtures__/update-addon-info/update-addon-info.input.js
rhalff/storybook
/* eslint-disable */ import React from 'react' import Button from './Button' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' storiesOf( 'Button' ).addWithInfo( 'simple usage', 'This is the basic usage with the button with providing a label to show the text.', () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ) ) storiesOf('Button').addWithInfo( 'simple usage (inline info)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true } ) storiesOf('Button').addWithInfo( 'simple usage (disable source)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { source: false, inline: true } ) storiesOf('Button').addWithInfo( 'simple usage (no header)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { header: false, inline: true } ) storiesOf('Button').addWithInfo( 'simple usage (no prop tables)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { propTables: false, inline: true } ) storiesOf('Button').addWithInfo( 'simple usage (custom propTables)', ` This is the basic usage with the button with providing a label to show the text. Since, the story source code is wrapped inside a div, info addon can't figure out propTypes on it's own. So, we need to give relevant React component classes manually using \`propTypes\` option as shown below: ~~~js storiesOf('Button') .addWithInfo( 'simple usage (custom propTables)', <info>, <storyFn>, { inline: true, propTables: [Button]} ); ~~~ `, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> </div> ), { inline: true, propTables: [Button] } ) storiesOf('Button').addWithInfo( 'simple usage (JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ) ) storiesOf('Button').addWithInfo( 'simple usage (inline JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true } ) storiesOf('Button').addWithInfo( 'simple usage (maxPropsInLine === 1)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true, maxPropsIntoLine: 1 } ) storiesOf('Button').addWithInfo( 'simple usage (maxPropObjectKeys === 5)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" object={{ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }} />, { inline: true, maxPropObjectKeys: 5 } ) storiesOf('Button').addWithInfo( 'simple usage (maxPropArrayLength === 8)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" array={[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} />, { inline: true, maxPropArrayLength: 8 } ) storiesOf('Button').addWithInfo( 'simple usage (maxPropStringLength === 10)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" string="1 2 3 4 5 6 7 8" />, { inline: true, maxPropStringLength: 5 } ) storiesOf('Button').addWithInfo( 'with custom styles', ` This is an example of how to customize the styles of the info components. For the full styles available, see \`./src/components/Story.js\` `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true, styles: stylesheet => { stylesheet.infoPage = { backgroundColor: '#ccc' } return stylesheet } } ) storiesOf('shared/ProgressBar', module) .addDecorator(withKnobs) .addWithInfo('default style', () => ( <ProgressBar progress={number('progress', 25)} delay={number('delay', 500)} /> ));
docs/app/Examples/elements/Segment/Variations/SegmentExampleEmphasisColoredInverted.js
aabustamante/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleEmphasisColoredInverted = () => ( <div> <Segment inverted color='red'> I'm here to tell you something, and you will probably read me first. </Segment> <Segment inverted color='red' secondary> I am pretty noticeable but you might check out other content before you look at me. </Segment> <Segment inverted color='red' tertiary> If you notice me you must be looking very hard. </Segment> </div> ) export default SegmentExampleEmphasisColoredInverted
src/components/Spinner.js
pshrmn/cryptonite
import React from 'react'; const Spinner = () => ( <svg width='32px' height='32px' xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" className="uil-ripple"> <rect x="0" y="0" width="100" height="100" fill="none" className="bk" /> <g> <animate attributeName="opacity" dur="2s" repeatCount="indefinite" begin="0s" keyTimes="0;0.33;1" values="1;1;0" /> <circle cx="50" cy="50" r="40" stroke="#d6b52c" fill="none" strokeWidth="6" strokeLinecap="round"> <animate attributeName="r" dur="2s" repeatCount="indefinite" begin="0s" keyTimes="0;0.33;1" values="0;22;44" /> </circle> </g> <g> <animate attributeName="opacity" dur="2s" repeatCount="indefinite" begin="1s" keyTimes="0;0.33;1" values="1;1;0" /> <circle cx="50" cy="50" r="40" stroke="#3863a7" fill="none" strokeWidth="6" strokeLinecap="round"> <animate attributeName="r" dur="2s" repeatCount="indefinite" begin="1s" keyTimes="0;0.33;1" values="0;22;44" /> </circle> </g> </svg> ); export default Spinner;
src/containers/Root/Root.js
jinglemansweep/webpack-boilerplate
import React from 'react'; // eslint-disable-line no-unused-vars import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; // eslint-disable-line no-unused-vars import { Route } from 'react-router'; // eslint-disable-line no-unused-vars import { ConnectedRouter } from 'react-router-redux'; // eslint-disable-line no-unused-vars import Home from '../Home/Home'; import Test from '../Test/Test'; const Root = ({ store, history }) => ( <Provider store={store}> <ConnectedRouter history={history}> <div> <Route exact path="/" component={Home}/> <Route path="/test" component={Test}/> </div> </ConnectedRouter> </Provider> ) Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired } export default Root
src/components/Bulk/BulkCreateView/SearchTerms/SearchTerms.js
City-of-Helsinki/helerm-ui
import React from 'react'; import PropTypes from 'prop-types'; import { isEmpty, slice } from 'lodash'; import { BULK_UPDATE_SEARCH_TERM_DEFAULT } from '../../../../constants'; import SearchTerm from './SearchTerm'; import './SearchTerms.scss'; export class SearchTerms extends React.Component { constructor (props) { super(props); this.onChangeSearchTerm = this.onChangeSearchTerm.bind(this); this.onAddSearchTerm = this.onAddSearchTerm.bind(this); this.onRemoveSearchTerm = this.onRemoveSearchTerm.bind(this); this.onResetSearch = this.onResetSearch.bind(this); this.onSearch = this.onSearch.bind(this); this.state = { searchTerms: props.searchTerms }; } onAddSearchTerm () { const { searchTerms } = this.state; this.setState({ searchTerms: [...searchTerms, { ...BULK_UPDATE_SEARCH_TERM_DEFAULT, id: new Date().getTime() }] }); this.props.resetSearchResults(); } onChangeSearchTerm (index, searchTerm) { const { searchTerms } = this.state; const start = slice(searchTerms, 0, index); const end = index + 1 < searchTerms.length ? slice(searchTerms, index + 1, searchTerms.length) : []; this.setState({ searchTerms: [...start, searchTerm, ...end] }); this.props.resetSearchResults(); } onRemoveSearchTerm (index) { const { searchTerms } = this.state; if (searchTerms.length === 1) { this.onResetSearch(); } else { const start = slice(searchTerms, 0, index); const end = index + 1 < searchTerms.length ? slice(searchTerms, index + 1, searchTerms.length) : []; this.setState({ searchTerms: [...start, ...end] }); } this.props.resetSearchResults(); } onResetSearch () { this.setState({ searchTerms: [{ ...BULK_UPDATE_SEARCH_TERM_DEFAULT, id: new Date().getTime() }] }); this.props.resetSearchResults(); } onSearch () { const { searchTerms } = this.state; this.props.onSearch(searchTerms); } validateTerms (searchTerms) { let isValidTerms = true; searchTerms.forEach(searchTerm => { if (isEmpty(searchTerm.target) || isEmpty(searchTerm.attribute) || isEmpty(searchTerm.value)) { isValidTerms = false; } }); return isValidTerms; } render () { const { attributeTypes, attributeValues } = this.props; const { searchTerms } = this.state; const isValidTerms = this.validateTerms(searchTerms); return ( <div className='search-terms'> <h3>Rajaa muutettavat kohteet</h3> <div className='search-terms-container'> {searchTerms.map((searchTerm, index) => ( <SearchTerm attributeTypes={attributeTypes} attributeValues={attributeValues} key={searchTerm.id} onAddSearchTerm={this.onAddSearchTerm} onChangeSearchTerm={(emittedSearchTerm) => this.onChangeSearchTerm(index, emittedSearchTerm)} onRemoveSearchTerm={() => this.onRemoveSearchTerm(index)} searchTerm={searchTerm} showAdd={index === searchTerms.length - 1} /> ))} </div> <div className='bulk-update-search-actions'> <button className='btn btn-default' onClick={this.onResetSearch}> Tyhjennä </button> <button className='btn btn-primary' disabled={!isValidTerms} onClick={this.onSearch} > Hae </button> </div> </div> ); } } SearchTerms.propTypes = { attributeTypes: PropTypes.object, attributeValues: PropTypes.object.isRequired, onSearch: PropTypes.func.isRequired, resetSearchResults: PropTypes.func.isRequired, searchTerms: PropTypes.array.isRequired }; export default SearchTerms;
src/svg-icons/device/access-alarms.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessAlarms = (props) => ( <SvgIcon {...props}> <path d="M22 5.7l-4.6-3.9-1.3 1.5 4.6 3.9L22 5.7zM7.9 3.4L6.6 1.9 2 5.7l1.3 1.5 4.6-3.8zM12.5 8H11v6l4.7 2.9.8-1.2-4-2.4V8zM12 4c-5 0-9 4-9 9s4 9 9 9 9-4 9-9-4-9-9-9zm0 16c-3.9 0-7-3.1-7-7s3.1-7 7-7 7 3.1 7 7-3.1 7-7 7z"/> </SvgIcon> ); DeviceAccessAlarms = pure(DeviceAccessAlarms); DeviceAccessAlarms.displayName = 'DeviceAccessAlarms'; DeviceAccessAlarms.muiName = 'SvgIcon'; export default DeviceAccessAlarms;
src/packages/@ncigdc/modern_components/AffectedCasesBarChart/AffectedCasesBarChart.js
NCI-GDC/portal-ui
// @flow import React from 'react'; import Relay from 'react-relay/classic'; import { parse } from 'query-string'; import { compose } from 'recompose'; import withRouter from '@ncigdc/utils/withRouter'; import { viewerQuery } from '@ncigdc/routes/queries'; import { parseFilterParam } from '@ncigdc/utils/uri'; import { Row, Column } from '@ncigdc/uikit/Flex'; import BarChart from '@ncigdc/components/Charts/BarChart'; import { withTheme } from '@ncigdc/theme'; import DownloadVisualizationButton from '@ncigdc/components/DownloadVisualizationButton'; import wrapSvg from '@ncigdc/utils/wrapSvg'; import { createClassicRenderer } from '@ncigdc/modern_components/Query'; const CHART_HEIGHT = 285; const COMPONENT_NAME = 'AffectedCasesBarChart'; class Route extends Relay.Route { static routeName = COMPONENT_NAME; static queries = viewerQuery; static prepareParams = ({ location: { search }, defaultFilters = null }) => { const q = parse(search); return { affectedCasesBarChart_filters: parseFilterParam( q.affectedCasesBarChart_filters, defaultFilters || null, ), }; }; } const createContainer = Component => Relay.createContainer(Component, { initialVariables: { affectedCasesBarChart_filters: null, score: 'gene.gene_id', }, fragments: { viewer: () => Relay.QL` fragment on Root { explore { allCases: cases { hits(first: 0) { total } } cases { hits (first: 20 filters: $affectedCasesBarChart_filters, score: $score) { total edges { node { score case_id submitter_id project { project_id } } } } } } } `, }, }); const Component = compose( withTheme, withRouter, )( ({ viewer: { explore: { cases = { hits: { edges: [] } } } }, theme, push, style, }) => { const chartData = cases.hits.edges.map(x => x.node).map(c => ({ fullLabel: c.submitter_id, label: c.submitter_id, value: c.score, tooltip: ( <span> <b>{c.submitter_id}</b> <br /> Project: {c.project.project_id} <br /> {c.score.toLocaleString()} Genes Affected </span> ), onClick: () => push(`/cases/${c.case_id}`), })); return ( <div style={style}> <Column style={{ padding: '0 0 0 2rem' }}> {cases && !!cases.hits.edges.length && ( <Row style={{ justifyContent: 'flex-end' }}> <DownloadVisualizationButton svg={() => wrapSvg({ selector: '#most-affected-cases svg', title: 'Most Affected Cases', })} data={chartData.map(d => ({ label: d.fullLabel, value: d.value, }))} slug="most-affected-cases-bar-chart" noText tooltipHTML="Download image or data" style={{ marginRight: '2rem' }} /> </Row> )} {cases && !!cases.hits.edges.length && ( <Row id="most-affected-cases"> <BarChart data={chartData} height={CHART_HEIGHT} margin={{ top: 20, right: 50, bottom: 85, left: 55 }} yAxis={{ title: '# Affected Genes' }} styles={{ xAxis: { stroke: theme.greyScale4, textFill: theme.greyScale3, }, yAxis: { stroke: theme.greyScale4, textFill: theme.greyScale3, }, bars: { fill: theme.secondary }, tooltips: { fill: '#fff', stroke: theme.greyScale4, textFill: theme.greyScale3, }, }} /> </Row> )} </Column> </div> ); }, ); export default createClassicRenderer( Route, createContainer(Component), CHART_HEIGHT, );
src/js/components/icons/base/FormFilter.js
odedre/grommet-final
/** * @description FormFilter 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. */ // (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}-form-filter`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-filter'); 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}><polygon fill="none" stroke="#000" strokeWidth="2" points="6 8 11.667 12.667 11.667 18 12.333 18 12.333 12.667 18 8 18 6 6 6"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'FormFilter'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
RNApp/app/index.js
spencercarli/react-native-meteor-boilerplate
import React from 'react'; import Meteor, { createContainer } from 'react-native-meteor'; import { AuthStack, Tabs } from './config/routes'; import Loading from './components/Loading'; import settings from './config/settings'; Meteor.connect(settings.METEOR_URL); const RNApp = (props) => { const { status, user, loggingIn } = props; if (status.connected === false || loggingIn) { return <Loading />; } else if (user !== null) { return <Tabs />; } return <AuthStack />; }; RNApp.propTypes = { status: React.PropTypes.object, user: React.PropTypes.object, loggingIn: React.PropTypes.bool, }; export default createContainer(() => { return { status: Meteor.status(), user: Meteor.user(), loggingIn: Meteor.loggingIn(), }; }, RNApp);
src/entypo/FolderImages.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--FolderImages'; let EntypoFolderImages = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M18.405,2.799C18.293,2.359,17.749,2,17.195,2H2.805c-0.555,0-1.099,0.359-1.21,0.799L1.394,4h17.211L18.405,2.799z M19.412,5H0.587C0.245,5-0.022,5.294,0.01,5.635l0.923,11.669C0.971,17.698,1.303,18,1.699,18H18.3c0.397,0,0.728-0.302,0.766-0.696l0.923-11.669C20.022,5.294,19.754,5,19.412,5z M12.438,8.375c0.518,0,0.938,0.42,0.938,0.938c0,0.518-0.42,0.938-0.938,0.938S11.5,9.83,11.5,9.312C11.5,8.795,11.92,8.375,12.438,8.375z M5.5,14l2.486-5.714l2.827,4.576l2.424-1.204L14.5,14H5.5z"/> </EntypoIcon> ); export default EntypoFolderImages;
js/components/sideBar/index.js
phamngoclinh/PetOnline_vs2
import React, { Component } from 'react'; import { Image, ScrollView, AsyncStorage } from 'react-native'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Content, Text, List, View, ListItem, Card, CardItem, Thumbnail, Button, Icon, Badge } from 'native-base'; import { setIndex } from '../../actions/list'; import navigateTo from '../../actions/sideBarNav'; import myTheme from '../../themes/base-theme'; import { closeDrawer } from '../../actions/drawer'; import GLOBAL from '../../storage/global'; import styles from './style'; const { replaceAt, } = actions; const apiLink = 'http://210.211.118.178/PetsAPI/'; const petAlbum = 'http://210.211.118.178/PetsAPI/Images/PetThumbnails/'; const userAlbum = 'http://210.211.118.178/PetsAPI/Images/UserThumbnails/'; var avatarThumbnail = ''; var coverThumbnail = ''; var user_Id = ''; var authToken = ''; class SideBar extends Component { static propTypes = { // setIndex: React.PropTypes.func, drawerState: React.PropTypes.string, navigateTo: React.PropTypes.func, replaceAt: React.PropTypes.func, closeDrawer: React.PropTypes.func, } constructor(props) { super(props); this.state = { user: '', avatar : '', username: '', email: '', phone: '', avatarThumbnail: '../../../images/avatar.png', coverThumbnail: '../../../images/avatar.png' }; } componentDidMount() { let _this = this; _this.getUserInformation(); this._loadInitialState(); } componentWillMount() { let _this = this; _this.getUserInformation(); } _loadInitialState () { let _this = this; try { AsyncStorage.getItem('AUTH_TOKEN').then((value) => { authToken = value; if (authToken !== null){ console.log("GET AUTH_TOKEN IN SIDEBAR: ", authToken ); // this.replaceRoute('home'); // alert("Check authToken is exist. authToken = " + authToken); _this.getUserInformation(); } else { try { console.log("Check authToken is NOT exist yet"); } catch (error) { // } } }); } catch (error) { // } }; navigateTo(route) { this.props.navigateTo(route, 'home'); } replaceRoute(route) { this.props.replaceAt('home', { key: route }, this.props.navigation.key); } logout() { let _this = this; user_Id = ''; AsyncStorage.setItem('USER_ID', ''); _this._removeToken().done(); _this.closeDrawer(); _this.replaceRoute('signin'); } getUserInformation() { let _this = this; AsyncStorage.getItem('USER_ID').then((value) => { console.log("UserId in sidebar: ", value); // alert("UserId in sidebar: ", value); user_Id = value; fetch('http://210.211.118.178/PetsAPI/api/userauthinfos/'+value, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Auth-Token': authToken } }) .then((response) => response.json()) .then((responseJson) => { // Store the results in the state variable results and set loading to _this.setState({ user: responseJson, username: responseJson.firstName + " " + responseJson.lastName, email: responseJson.email, phone: responseJson.phone, is_loading_data: false }); AsyncStorage.setItem('USER_EMAIL', responseJson.email); avatarThumbnail = responseJson.avatarThumbnail; coverThumbnail = responseJson.coverThumbnail; if(avatarThumbnail == null || avatarThumbnail == '') { avatarThumbnail = '../../../images/avatar.png'; } if(coverThumbnail == null || coverThumbnail == '') { coverThumbnail = '../../../images/avatar.png'; } console.log("Get USER from server: ", responseJson); }) .catch((error) => { _this.setState({ loading: false }); console.error(error); }); }); } _removeToken = async () => { try { await AsyncStorage.removeItem('AUTH_TOKEN'); } catch (error) { } }; closeDrawer() { if (this.props.drawerState === 'opened') { this.props.closeDrawer(); } } render() { return ( <Content theme={myTheme} style={styles.sidebar} > <View style={styles.top}> <Image style={styles.topWrapper} source={require('../../../images/avatar.png')} > <Card style={{backgroundColor: '#f5f5f5', borderWidth: 0, padding: 20}}> { user_Id ? ( <CardItem style={{borderBottomWidth: 0}}> <Thumbnail style={{width: 70, height: 70, borderRadius: 100, marginRight: 10}} source={{uri : userAlbum + avatarThumbnail}} /> <Text style={{color: '#384850', fontSize: 25}} numberOfLines={1}>{this.state.username}</Text> <Text note style={{color: '#384850', fontSize: 17}} numberOfLines={1}>{this.state.email}</Text> </CardItem> ) : ( <CardItem style={{borderBottomWidth: 0}}> <Thumbnail style={{width: 70, height: 70, borderRadius: 100, marginRight: 10}} source={require('../../../images/avatar.png')} /> <Text>Anonymous</Text> <Text>anonymous@gmail.com</Text> </CardItem> ) } </Card> </Image> </View> <ScrollView style={styles.middle}> <List> <ListItem button iconLeft onPress={() => this.navigateTo('home')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-home-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>TRANG CHỦ</Text> </ListItem> <ListItem button iconLeft onPress={() => this.navigateTo('category')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-bookmarks-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>DANH MỤC</Text> <Badge primary style={{paddingTop: 0}}>6</Badge> </ListItem> { /* <ListItem button iconLeft onPress={() => this.navigateTo('createPet')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-add-circle-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>TẠO THÚ CƯNG</Text> </ListItem> */ } <ListItem button iconLeft onPress={() => this.navigateTo('createPet')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-book-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>TẠO BÀI VIẾT</Text> </ListItem> { /* <ListItem button iconLeft onPress={() => this.navigateTo('signin')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-log-in" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Sign In</Text> </ListItem> <ListItem button iconLeft onPress={() => this.navigateTo('signup')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-log-in" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Sign Up</Text> </ListItem> */ } { /* <ListItem button iconLeft onPress={() => this.navigateTo('forgetPassword')}> <Icon name="ios-plane" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Forget Password</Text> <Text note>Off</Text> </ListItem> */ } { /* <ListItem button iconLeft onPress={() => this.navigateTo('detail')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-settings-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Detail</Text> <Badge style={{ backgroundColor: '#8C97B5' }}>2</Badge> </ListItem> */ } <ListItem button iconLeft onPress={() => this.navigateTo('profile')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-contact-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>THÔNG TIN CÁ NHÂN</Text> </ListItem> { /* <ListItem button iconLeft onPress={() => this.navigateTo('search')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-settings-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Search</Text> <Badge style={{ backgroundColor: '#8C97B5' }}>2</Badge> </ListItem> <ListItem button iconLeft onPress={() => this.navigateTo('blankPage')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-settings-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>Blank Page</Text> </ListItem> */ } <ListItem button iconLeft onPress={() => this.navigateTo('blankPage')} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20}}> <Icon name="ios-people-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>PHÒNG TÁN GẪU</Text> </ListItem> <ListItem button iconLeft onPress={() => this.logout()} style={{marginTop: 10, marginBottom: 10, borderBottomColor: '#f3f3f3', paddingBottom: 20, borderBottomWidth: 0}}> <Icon name="ios-log-out-outline" style={{ color: '#0A69FE', fontSize: 26, marginRight: 15 }} /> <Text style={{fontSize: 19, color: '#384850'}}>ĐĂNG XUẤT</Text> </ListItem> </List> </ScrollView> <Card style={styles.bottom}> <CardItem style={{borderBottomWidth: 0, borderRightWidth: 0, borderLeftWidth: 0, borderRadius: 0, borderTopColor: '#fdfdfd', alignSelf: 'flex-end'}}> <Text note>Copyright 2016...</Text> </CardItem> </Card> </Content> ); } } function bindAction(dispatch) { return { setIndex: index => dispatch(setIndex(index)), closeDrawer: () => dispatch(closeDrawer()), navigateTo: (route, homeRoute) => dispatch(navigateTo(route, homeRoute)), replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)), }; } const mapStateToProps = state => ({ drawerState: state.drawer.drawerState, navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(SideBar);
client/src/components/Loading.js
hutchgrant/react-boilerplate
import React from 'react'; export default({isLoading, error}) => { // Handle the loading state if (isLoading) { return <div>Loading...</div>; } // Handle the error state else if (error) { return ( <div className="text-center"> <h1>Error 404</h1> <h3>Page Not Found</h3> <p>Sorry the page you're looking for either doesn't exist or has moved.</p> </div> ); } else { return null; } };
jenkins-design-language/src/js/components/material-ui/svg-icons/hardware/laptop-chromebook.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareLaptopChromebook = (props) => ( <SvgIcon {...props}> <path d="M22 18V3H2v15H0v2h24v-2h-2zm-8 0h-4v-1h4v1zm6-3H4V5h16v10z"/> </SvgIcon> ); HardwareLaptopChromebook.displayName = 'HardwareLaptopChromebook'; HardwareLaptopChromebook.muiName = 'SvgIcon'; export default HardwareLaptopChromebook;
src/react.js
TribeMedia/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
src/index.js
jlhall/D3Rand_Builder
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/components/Logout.js
ikafire/OpenObjectMarker
import React from 'react'; import cookie from 'react-cookie'; class Logout extends React.Component { render() { cookie.save('username', '', { path: '/' }); console.log(cookie.load('username')); return ( <div className='container'> <h1> Open Object Marker </h1> <ul> <li><a href="/home">Home</a></li> <li><a href="/upload">Upload</a></li> <li><a href="/label">Label</a></li> <li><a href="/explore">Explore</a></li> <li><a href="/login">Login</a></li> </ul> <hr></hr> <p>You have loged out!</p> </div> ); } } export default Logout;
src/components/foodItemTable.js
ColdForge/icebox
import React, { Component } from 'react'; import { Table, TableBody } from 'material-ui/Table'; import FoodItemTableEntry from './foodItemTableEntry'; // import { v4 } from 'node-uuid'; // const tableData = [ // { // name: 'Pizza', // }, // { // name: 'Milk', // }, // { // name: 'Steak', // }, // { // name: 'Chicken', // }, // { // name: 'Green Beans', // }, // { // name: 'Yogurt', // }, // ]; class FoodItemTable extends Component { constructor(props) { super(props); this.state = { toggled: true, showCheckboxes: false, }; } handleToggle = (event, toggled) => { this.props.discarded(event.target.name); this.setState({ [event.target.name]: toggled }); }; handleChange = (event) => { this.setState({ height: event.target.value }); }; render() { return ( <Table> <TableBody displayRowCheckbox={this.state.showCheckboxes} > {this.props.items.map((row, index) => ( <FoodItemTableEntry name={row} i={index} toggle={this.handleToggle} toggled={this.state.toggled} /> ))} </TableBody> </Table> ); } } FoodItemTable.propTypes = { discarded: React.PropTypes.func, items: React.PropTypes.array, }; export default FoodItemTable;
react/src/base/inputs/SprkRevealInput/SprkRevealInput.js
sparkdesignsystem/spark-design-system
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import uniqueId from 'lodash/uniqueId'; import classNames from 'classnames'; import SprkTextInput from '../SprkTextInput/SprkTextInput'; /** * TODO: Remove this component as part of Issue #3780. */ class SprkRevealInput extends Component { constructor(props) { super(props); this.state = { revealControlId: uniqueId(), isRevealed: false, }; this.toggleReveal = this.toggleReveal.bind(this); } toggleReveal() { this.setState((prevState) => ({ isRevealed: !prevState.isRevealed, })); } render() { const { isRevealed, revealControlId } = this.state; const { toggleLabel, disabled, ...rest } = this.props; return ( <SprkTextInput type={isRevealed ? 'text' : 'password'} disabled={disabled} {...rest} > <div className=" sprk-b-Checkbox sprk-b-SelectionContainer sprk-b-InputContainer__visibility-toggle" > <input className="sprk-b-Checkbox__input" id={revealControlId} type="checkbox" onClick={this.toggleReveal} disabled={disabled} /> <label htmlFor={revealControlId} className={classNames( 'sprk-b-Label sprk-b-Label--inline sprk-b-Checkbox__label', { 'sprk-b-Label--disabled': disabled }, )} > {toggleLabel} </label> </div> </SprkTextInput> ); } } SprkRevealInput.propTypes = { /** * A space-separated string of classes to add to * the outermost container of the component. */ additionalClasses: PropTypes.string, /** * Assigned to the `data-analytics` attribute serving as a unique selector * for outside libraries to capture data. */ analyticsString: PropTypes.string, /** * A function supplied will be passed * the value of the input and then executed, * if the valid prop is true. The value * returned will be assigned to the value of the input. */ formatter: PropTypes.func, /** * Text that appears below the input, * intended to provide more information to a user. */ helperText: PropTypes.string, /** * If true, will visually hide the label, * using the value of the label prop as screen reader only text. */ hiddenLabel: PropTypes.bool, /** * Assigned to the `data-id` attribute serving as a * unique selector for automated tools. */ idString: PropTypes.string, /** * The text to render inside the label element. */ label: PropTypes.string, /** * The name of the icon, when supplied, * will be rendered inside the input element. */ leadingIcon: PropTypes.string, /** * If true, will render the * currency icon inside the input element. */ textIcon: PropTypes.bool, /** * The text explaining the checkbox * that toggles the visibility of the input's content. */ toggleLabel: PropTypes.string, /** * Determines whether to render the * component in the valid or the error state. */ valid: PropTypes.bool, /** * If true, will render the component in the disabled state. */ disabled: PropTypes.bool, }; SprkRevealInput.defaultProps = { formatter: (value) => value, helperText: '', hiddenLabel: false, label: 'Text Input Label', textIcon: false, toggleLabel: 'Show Value', valid: true, }; export default SprkRevealInput;
packages/ui-toolkit/src/form/label.js
yldio/joyent-portal
import React from 'react'; import { Subscriber } from 'joy-react-broadcast'; import is from 'styled-is'; import remcalc from 'remcalc'; import styled from 'styled-components'; import Label from '../label'; const StyledLabel = styled(Label)` font-weight: ${props => props.theme.font.weight.semibold}; white-space: pre; font-size: ${remcalc(13)}; ${is('actionable')` cursor: pointer; `}; ${is('disabled')` color: ${props => props.theme.grey}; `}; ${is('big')` font-size: ${remcalc(15)}; `}; ${is('normal')` font-weight: ${props => props.theme.font.weight.normal}; `}; `; export default props => { const render = value => { const { id = '' } = value || {}; return <StyledLabel {...props} htmlFor={id} />; }; return <Subscriber channel="input-group">{render}</Subscriber>; };
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/source/src/app/components/Base/Header/Header.js
ChamNDeSilva/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react' import {Link, withRouter} from "react-router-dom"; import AuthManager from '../../../data/AuthManager.js'; import qs from 'qs' import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import IconButton from 'material-ui/IconButton'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import Menu, { MenuItem } from 'material-ui/Menu'; import SearchIcon from 'material-ui-icons/Search'; import MenuIcon from 'material-ui-icons/Menu'; import PlaylistAddIcon from 'material-ui-icons/PlaylistAdd'; import CloseIcon from 'material-ui-icons/Close'; import TextField from 'material-ui/TextField'; import InfoIcon from 'material-ui-icons/Info'; import InfoLightBulb from 'material-ui-icons/LightbulbOutline'; import Avatar from 'material-ui/Avatar'; import List, { ListItem, ListItemIcon, ListItemText, } from 'material-ui/List'; const helpTips = [ "By API Name [Default]", "By API Provider [ Syntax - provider:xxxx ] or", "By API Version [ Syntax - version:xxxx ] or", "By Context [ Syntax - context:xxxx ] or", "By Description [ Syntax - description:xxxx ] or", "By Tags [ Syntax - tags:xxxx ] or", "By Sub-Context [ Syntax - subcontext:xxxx ] or", "By Documentation Content [ Syntax - doc:xxxx ]" ]; class Header extends React.Component { constructor(props){ super(props); this.state = { anchorElUserMenu: undefined, anchorElAddMenu: undefined, anchorElMainMenu: undefined, anchorElTips: undefined, openUserMenu: false, openAddMenu: false, openMainMenu: false, searchVisible: false, openTips: false } } handleClickUserMenu = event => { this.setState({ openUserMenu: true, anchorElUserMenu: event.currentTarget }); }; handleRequestCloseUserMenu = () => { this.setState({ openUserMenu: false }); }; handleClickAddMenu = event => { this.setState({ openAddMenu: true, anchorElAddMenu: event.currentTarget }); }; handleRequestCloseAddMenu = () => { this.setState({ openAddMenu: false }); }; handleClickMainMenu = event => { this.setState({ openMainMenu: true, anchorElMainMenu: event.currentTarget }); }; handleRequestCloseMainMenu = () => { this.setState({ openMainMenu: false }); }; toggleSearch = () => { this.setState({searchVisible:!this.state.searchVisible}); } handleClickTips = event => { this.setState({ openTips: true, anchorElTips: event.currentTarget }); }; handleRequestCloseTips = () => { this.setState({ openTips: false }); }; componentWillReceiveProps(nextProps){ if(nextProps.showLeftMenu){ this.setState({showLeftMenu:nextProps.showLeftMenu}); } } render(props) { let user = AuthManager.getUser(); const focusUsernameInputField = input => { input && input.focus(); }; return ( <AppBar position="static"> {this.state.searchVisible ? <Toolbar> <IconButton aria-label="Search" color="contrast"> <CloseIcon onClick={this.toggleSearch}/> </IconButton> <TextField id="placeholder" InputProps={{ placeholder: 'Placeholder' }} helperText="Search By Name" fullWidth margin="normal" color = "contrast" inputRef={focusUsernameInputField} /> <IconButton aria-label="Search Info" color="contrast"> <InfoLightBulb onClick={this.handleClickTips}/> </IconButton> <Menu id="tip-menu" anchorEl={this.state.anchorElTips} open={this.state.openTips} onRequestClose={this.handleRequestCloseTips} > <List dense={true}> {helpTips.map((tip) => { return <ListItem button key={tip}> <ListItemIcon><InfoIcon /></ListItemIcon> <ListItemText primary={tip} /> </ListItem> })} </List> </Menu> </Toolbar> : <Toolbar> {this.state.showLeftMenu ? <IconButton color="contrast" aria-label="Menu"> <MenuIcon color="contrast" onClick={this.props.toggleDrawer}/> </IconButton> : <span></span> } <Typography type="title" color="inherit" style={{flex: 1}}> <Link to="/" className="home"> <img className="brand" src="/store/public/images/logo-inverse.svg" alt="wso2-logo"/> <span color="contrast" style={{fontSize: "15px", color:"#fff"}}>APIM Store</span> </Link> </Typography> { user ? <div style={{display:"flex"}}> <Button aria-label="Search" onClick={this.toggleSearch} color="contrast"> <SearchIcon /> </Button> <Button aria-owns="simple-menu" aria-haspopup="true" onClick={this.handleClickMainMenu} color="contrast"> <MenuIcon /> </Button> <Menu id="simple-menu" anchorEl={this.state.anchorElMainMenu} open={this.state.openMainMenu} onRequestClose={this.handleRequestCloseMainMenu} style={{alignItems: "center", justifyContent: "center"}} > <MenuItem onClick={this.handleRequestCloseMainMenu}> <Link to="/" style={{color: "#000", textDecoration: 'none'}}>List API</Link> </MenuItem> <MenuItem onClick={this.handleRequestCloseMainMenu}> <Link to="/applications" style={{color: "#000", textDecoration: 'none'}}>Applications</Link> </MenuItem> </Menu> {/* User menu */} <Button aria-owns="simple-menu" aria-haspopup="true" onClick={this.handleClickUserMenu} color="contrast"> <Avatar alt="{user.name}" src="/store/public/images/users/user.png" style={{marginRight:"5px"}}></Avatar> <span style={{textTransform:"none", marginLeft:"5px"}}>{user.name}</span> </Button> <Menu id="simple-menu" anchorEl={this.state.anchorElUserMenu} open={this.state.openUserMenu} onRequestClose={this.handleRequestCloseUserMenu} style={{alignItems: "center", justifyContent: "center"}} > <MenuItem onClick={this.handleRequestCloseUserMenu}>Change Password</MenuItem> <MenuItem onClick={this.handleRequestCloseUserMenu}> <Link to="/logout" style={{color: "#000", textDecoration: 'none'}}>Logout</Link> </MenuItem> </Menu> </div> : <div></div> } </Toolbar> } </AppBar> ); } } export default withRouter(Header)
react/features/settings/components/web/video/VideoSettingsContent.js
jitsi/jitsi-meet
// @flow import React, { Component } from 'react'; import { translate } from '../../../../base/i18n'; import Video from '../../../../base/media/components/Video'; import { equals } from '../../../../base/redux'; import { createLocalVideoTracks } from '../../../functions'; const videoClassName = 'video-preview-video flipVideoX'; /** * The type of the React {@code Component} props of {@link VideoSettingsContent}. */ export type Props = { /** * The deviceId of the camera device currently being used. */ currentCameraDeviceId: string, /** * Callback invoked to change current camera. */ setVideoInputDevice: Function, /** * Invoked to obtain translated strings. */ t: Function, /** * Callback invoked to toggle the settings popup visibility. */ toggleVideoSettings: Function, /** * All the camera device ids currently connected. */ videoDeviceIds: string[], }; /** * The type of the React {@code Component} state of {@link VideoSettingsContent}. */ type State = { /** * An array of all the jitsiTracks and eventual errors. */ trackData: Object[], }; /** * Implements a React {@link Component} which displays a list of video * previews to choose from. * * @augments Component */ class VideoSettingsContent extends Component<Props, State> { _componentWasUnmounted: boolean; _videoContentRef: Object; /** * Initializes a new {@code VideoSettingsContent} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); this._onEscClick = this._onEscClick.bind(this); this._videoContentRef = React.createRef(); this.state = { trackData: new Array(props.videoDeviceIds.length).fill({ jitsiTrack: null }) }; } _onEscClick: (KeyboardEvent) => void; /** * Click handler for the video entries. * * @param {KeyboardEvent} event - Esc key click to close the popup. * @returns {void} */ _onEscClick(event) { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this._videoContentRef.current.style.display = 'none'; } } /** * Creates and updates the track data. * * @returns {void} */ async _setTracks() { this._disposeTracks(this.state.trackData); const trackData = await createLocalVideoTracks(this.props.videoDeviceIds, 5000); // In case the component gets unmounted before the tracks are created // avoid a leak by not setting the state if (this._componentWasUnmounted) { this._disposeTracks(trackData); } else { this.setState({ trackData }); } } /** * Destroys all the tracks from trackData object. * * @param {Object[]} trackData - An array of tracks that are to be disposed. * @returns {Promise<void>} */ _disposeTracks(trackData) { trackData.forEach(({ jitsiTrack }) => { jitsiTrack && jitsiTrack.dispose(); }); } /** * Returns the click handler used when selecting the video preview. * * @param {string} deviceId - The id of the camera device. * @returns {Function} */ _onEntryClick(deviceId) { return () => { this.props.setVideoInputDevice(deviceId); this.props.toggleVideoSettings(); }; } /** * Renders a preview entry. * * @param {Object} data - The track data. * @param {number} index - The index of the entry. * @returns {React$Node} */ _renderPreviewEntry(data, index) { const { error, jitsiTrack, deviceId } = data; const { currentCameraDeviceId, t } = this.props; const isSelected = deviceId === currentCameraDeviceId; const key = `vp-${index}`; const className = 'video-preview-entry'; const tabIndex = '0'; if (error) { return ( <div className = { className } key = { key } tabIndex = { -1 } > <div className = 'video-preview-error'>{t(error)}</div> </div> ); } const props: Object = { className, key, tabIndex }; const label = jitsiTrack && jitsiTrack.getTrackLabel(); if (isSelected) { props['aria-checked'] = true; props.className = `${className} video-preview-entry--selected`; } else { props.onClick = this._onEntryClick(deviceId); props.onKeyPress = e => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); props.onClick(); } }; } return ( <div { ...props } role = 'radio'> <div className = 'video-preview-label'> {label && <div className = 'video-preview-label-container'> <div className = 'video-preview-label-text'> <span>{label}</span></div> </div>} </div> <div className = 'video-preview-overlay' /> <Video className = { videoClassName } playsinline = { true } videoTrack = {{ jitsiTrack }} /> </div> ); } /** * Implements React's {@link Component#componentDidMount}. * * @inheritdoc */ componentDidMount() { this._setTracks(); } /** * Implements React's {@link Component#componentWillUnmount}. * * @inheritdoc */ componentWillUnmount() { this._componentWasUnmounted = true; this._disposeTracks(this.state.trackData); } /** * Implements React's {@link Component#componentDidUpdate}. * * @inheritdoc */ componentDidUpdate(prevProps) { if (!equals(this.props.videoDeviceIds, prevProps.videoDeviceIds)) { this._setTracks(); } } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { trackData } = this.state; return ( <div aria-labelledby = 'video-settings-button' className = 'video-preview-container' id = 'video-settings-dialog' onKeyDown = { this._onEscClick } ref = { this._videoContentRef } role = 'radiogroup' tabIndex = '-1'> {trackData.map((data, i) => this._renderPreviewEntry(data, i))} </div> ); } } export default translate(VideoSettingsContent);
fixtures/fiber-debugger/src/Fibers.js
jordanpapaleo/react
import React from 'react'; import { Motion, spring } from 'react-motion'; import dagre from 'dagre'; // import prettyFormat from 'pretty-format'; // import reactElement from 'pretty-format/plugins/ReactElement'; function getFiberColor(fibers, id) { if (fibers.currentIDs.indexOf(id) > -1) { return 'lightgreen'; } if (id === fibers.workInProgressID) { return 'yellow'; } return 'lightyellow'; } function Graph(props) { var g = new dagre.graphlib.Graph(); g.setGraph({ width: 1000, height: 1000, nodesep: 50, edgesep: 150, ranksep: 150, marginx: 100, marginy: 100, }); var edgeLabels = {}; React.Children.forEach(props.children, function(child) { if (!child) { return; } if (child.type.isVertex) { g.setNode(child.key, { label: child, width: child.props.width, height: child.props.height }); } else if (child.type.isEdge) { const relationshipKey = child.props.source + ':' + child.props.target; if (!edgeLabels[relationshipKey]) { edgeLabels[relationshipKey] = []; } edgeLabels[relationshipKey].push(child); } }); Object.keys(edgeLabels).forEach(key => { const children = edgeLabels[key]; const child = children[0]; g.setEdge(child.props.source, child.props.target, { label: child, allChildren: children.map(c => c.props.children), weight: child.props.weight }); }); dagre.layout(g); var activeNode = g.nodes().map(v => g.node(v)).find(node => node.label.props.isActive ); const [winX, winY] = [window.innerWidth / 2, window.innerHeight / 2] var focusDx = activeNode ? (winX - activeNode.x) : 0; var focusDy = activeNode ? (winY - activeNode.y) : 0; var nodes = g.nodes().map(v => { var node = g.node(v); return ( <Motion style={{ x: props.isDragging ? node.x + focusDx : spring(node.x + focusDx), y: props.isDragging ? node.y + focusDy : spring(node.y + focusDy) }} key={node.label.key}> {interpolatingStyle => React.cloneElement(node.label, { x: interpolatingStyle.x + props.dx, y: interpolatingStyle.y + props.dy, vanillaX: node.x, vanillaY: node.y, }) } </Motion> ); }); var edges = g.edges().map(e => { var edge = g.edge(e); let idx = 0; return ( <Motion style={edge.points.reduce((bag, point) => { bag[idx + ':x'] = props.isDragging ? point.x + focusDx : spring(point.x + focusDx); bag[idx + ':y'] = props.isDragging ? point.y + focusDy : spring(point.y + focusDy); idx++; return bag; }, {})} key={edge.label.key}> {interpolatedStyle => { let points = []; Object.keys(interpolatedStyle).forEach(key => { const [idx, prop] = key.split(':'); if (!points[idx]) { points[idx] = { x: props.dx, y: props.dy }; } points[idx][prop] += interpolatedStyle[key]; }); return React.cloneElement(edge.label, { points, id: edge.label.key, children: edge.allChildren.join(', ') }); }} </Motion> ); }); return ( <div style={{ position: 'relative', height: '100%' }}> {edges} {nodes} </div> ); } function Vertex(props) { if (Number.isNaN(props.x) || Number.isNaN(props.y)) { return null; } return ( <div style={{ position: 'absolute', border: '1px solid black', left: (props.x-(props.width/2)), top: (props.y-(props.height/2)), width: props.width, height: props.height, overflow: 'hidden', padding: '4px', wordWrap: 'break-word' }}> {props.children} </div> ); } Vertex.isVertex = true; const strokes = { alt: 'blue', child: 'green', sibling: 'darkgreen', return: 'red', fx: 'purple', progressedChild: 'cyan', progressedDel: 'brown' }; function Edge(props) { var points = props.points; var path = "M" + points[0].x + " " + points[0].y + " "; if (!points[0].x || !points[0].y) { return null; } for (var i = 1; i < points.length; i++) { path += "L" + points[i].x + " " + points[i].y + " "; if (!points[i].x || !points[i].y) { return null; } } var lineID = props.id; return ( <svg width="100%" height="100%" style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }}> <defs> <path d={path} id={lineID} /> <marker id="markerCircle" markerWidth="8" markerHeight="8" refX="5" refY="5"> <circle cx="5" cy="5" r="3" style={{stroke: 'none', fill:'black'}}/> </marker> <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto"> <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: 'black'}} /> </marker> </defs> <use xlinkHref={`#${lineID}`} fill="none" stroke={strokes[props.kind]} style={{ markerStart: 'url(#markerCircle)', markerEnd: 'url(#markerArrow)' }} /> <text> <textPath xlinkHref={`#${lineID}`}> {'     '}{props.children} </textPath> </text> </svg> ); } Edge.isEdge = true; function formatPriority(priority) { switch (priority) { case 1: return 'synchronous'; case 2: return 'task'; case 3: return 'animation'; case 4: return 'hi-pri work'; case 5: return 'lo-pri work'; case 6: return 'offscreen work'; default: throw new Error('Unknown priority.'); } } export default function Fibers({ fibers, show, ...rest }) { const items = Object.keys(fibers.descriptions).map(id => fibers.descriptions[id] ); const isDragging = rest.className.indexOf('dragging') > -1; const [_, sdx, sdy] = rest.style.transform.match(/translate\((-?\d+)px,(-?\d+)px\)/) || []; const dx = Number(sdx); const dy = Number(sdy); return ( <div {...rest} style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, ...rest.style, transform: null }}> <Graph className="graph" dx={dx} dy={dy} isDragging={isDragging} > {items.map(fiber => [ <Vertex key={fiber.id} width={200} height={100} isActive={fiber.id === fibers.workInProgressID}> <div style={{ width: '100%', height: '100%', backgroundColor: getFiberColor(fibers, fiber.id) }} title={ /*prettyFormat(fiber, { plugins: [reactElement ]})*/ 'todo: this was hanging last time I tried to pretty print' }> <small>{fiber.tag} #{fiber.id}</small> <br /> {fiber.type} <br /> {fibers.currentIDs.indexOf(fiber.id) === -1 ? <small> {fiber.pendingWorkPriority !== 0 && [ <span style={{ fontWeight: fiber.pendingWorkPriority <= fiber.progressedPriority ? 'bold' : 'normal' }} key="span"> Needs: {formatPriority(fiber.pendingWorkPriority)} </span>, <br key="br" /> ]} {fiber.progressedPriority !== 0 && [ `Finished: ${formatPriority(fiber.progressedPriority)}`, <br key="br" /> ]} {fiber.memoizedProps !== null && fiber.pendingProps !== null && [ fiber.memoizedProps === fiber.pendingProps ? 'Can reuse memoized.' : 'Cannot reuse memoized.', <br /> ]} </small> : <small> Committed </small> } </div> </Vertex>, fiber.child && show.child && <Edge source={fiber.id} target={fiber.child} kind="child" weight={1000} key={`${fiber.id}-${fiber.child}-child`}> child </Edge>, fiber.progressedChild && show.progressedChild && <Edge source={fiber.id} target={fiber.progressedChild} kind="progressedChild" weight={1000} key={`${fiber.id}-${fiber.progressedChild}-pChild`}> pChild </Edge>, fiber.sibling && show.sibling && <Edge source={fiber.id} target={fiber.sibling} kind="sibling" weight={2000} key={`${fiber.id}-${fiber.sibling}-sibling`}> sibling </Edge>, fiber.return && show.return && <Edge source={fiber.id} target={fiber.return} kind="return" weight={1000} key={`${fiber.id}-${fiber.return}-return`}> return </Edge>, fiber.nextEffect && show.fx && <Edge source={fiber.id} target={fiber.nextEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.nextEffect}-nextEffect`}> nextFx </Edge>, fiber.firstEffect && show.fx && <Edge source={fiber.id} target={fiber.firstEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.firstEffect}-firstEffect`}> firstFx </Edge>, fiber.lastEffect && show.fx && <Edge source={fiber.id} target={fiber.lastEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.lastEffect}-lastEffect`}> lastFx </Edge>, fiber.progressedFirstDeletion && show.progressedDel && <Edge source={fiber.id} target={fiber.progressedFirstDeletion} kind="progressedDel" weight={100} key={`${fiber.id}-${fiber.progressedFirstDeletion}-pFD`}> pFDel </Edge>, fiber.progressedLastDeletion && show.progressedDel && <Edge source={fiber.id} target={fiber.progressedLastDeletion} kind="progressedDel" weight={100} key={`${fiber.id}-${fiber.progressedLastDeletion}-pLD`}> pLDel </Edge>, fiber.alternate && show.alt && <Edge source={fiber.id} target={fiber.alternate} kind="alt" weight={10} key={`${fiber.id}-${fiber.alternate}-alt`}> alt </Edge>, ])} </Graph> </div> ); }