path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/modules/home/components/Disclaimer.js
nordsoftware/outdoors-sports-map
import React from 'react'; import {Link} from 'react-router'; import {translate} from 'react-i18next'; export default translate()(({attributionLink, t}) => <div className="disclaimer"> <div className="disclaimer__content"> <Link to="#">{t('APP.ABOUT')}</Link> <a target="_blank" href={attributionLink}>{t('MAP.ATTRIBUTION')} </a> </div> </div> );
client/views/admin/apps/AppsPage.js
VoiSmart/Rocket.Chat
import { Button, ButtonGroup, Icon } from '@rocket.chat/fuselage'; import React from 'react'; import Page from '../../../components/Page'; import { useRoute } from '../../../contexts/RouterContext'; import { useSetting } from '../../../contexts/SettingsContext'; import { useTranslation } from '../../../contexts/TranslationContext'; import AppsTable from './AppsTable'; function AppsPage() { const t = useTranslation(); const isDevelopmentMode = useSetting('Apps_Framework_Development_Mode'); const marketplaceRoute = useRoute('admin-marketplace'); const appsRoute = useRoute('admin-apps'); const handleUploadButtonClick = () => { appsRoute.push({ context: 'install' }); }; const handleViewMarketplaceButtonClick = () => { marketplaceRoute.push(); }; return ( <Page> <Page.Header title={t('Apps')}> <ButtonGroup> {isDevelopmentMode && ( <Button primary onClick={handleUploadButtonClick}> <Icon size='x20' name='upload' /> {t('Upload_app')} </Button> )} <Button primary onClick={handleViewMarketplaceButtonClick}> <Icon size='x20' name='download' /> {t('Marketplace_view_marketplace')} </Button> </ButtonGroup> </Page.Header> <Page.Content> <AppsTable /> </Page.Content> </Page> ); } export default AppsPage;
components/PendingGame.js
ttalhouk/Game_On
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TabBarIOS, Text, View, TouchableHighlight, ListView, ActivityIndicatorIOS, } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; const styles = require('../components/styling.js') class PendingGame extends Component { constructor(props){ super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), userInfo: {}, loading: true, } } back(){ this.props.navigator.pop(); } challengeTeam(game) { fetch(GLOBAL.ngrok+'/players/'+this.props.userInfo.info.id+'/teams/'+this.props.userInfo.team.id+'/games/'+game.game_id+'/challenge', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }) .then((response) => response.json()) .then((response) => { if (response.error) { console.log(response) this.setState({ errorMessages: response.errorMessages }) }else{ console.log(response); } this.back(); }) } componentWillMount(){ this.getPendingGame(); this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.props.userInfo.team) }); } getPendingGame() { fetch(GLOBAL.ngrok+'/players/'+this.props.userInfo.info.id+'/teams/'+this.props.userInfo.team.id+'/play', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }) .then((response) => response.json()) .then((response) => { if (response.error) { // this is incorrect credentials this.setState({ errorMessages: response.errorMessages }) }else{ this.setState({ gameInfo: response.games, dataSource: this.state.dataSource.cloneWithRows(response.games), loading: false, }); } }); } renderGame(game){ game.home_team.name = game.home_team.name[0].toUpperCase() + game.home_team.name.substring(1); return ( <View style={styles.innerWrapper}> <View> <TouchableHighlight onPress={this.challengeTeam.bind(this, game)}> <Text style={[styles.h1]}>{game.home_team.name}</Text> </TouchableHighlight> </View> <View> <Text style={[styles.h4]}>{game.start_time}</Text> <Text style={[styles.h5]}>{game.address}</Text> <Text style={[styles.h5]}>{game.city}, {game.zip_code}</Text> </View> </View> ) } renderLoadingView() { return ( <ActivityIndicatorIOS animating={this.state.animating} style={[styles.centering, {height: 500}]} size="large" /> ) } render() { if (this.state.loading) { return this.renderLoadingView(); } return ( <View style={styles.container}> <View style={styles.header}> <Text style={[styles.headerText]}>Play Games</Text> </View> <ListView dataSource={this.state.dataSource} renderRow={this.renderGame.bind(this)} /> </View> ) } } module.exports = PendingGame;
examples/complex/src/components/repo/data.js
rocjs/roc-package-web-app-react
import React, { Component } from 'react'; import styles from './style.css'; export default class RepoData extends Component { static propTypes = { city: React.PropTypes.object, list: React.PropTypes.array }; render() { const repos = []; Object.keys(this.props).forEach((repo, i) => { const repoData = this.props[repo]; repos.push( <div key={ i }> <ul className={ styles.list }> <li> <h2>{ repoData.name }</h2> </li> <li> Stargazers: { repoData.stargazers_count } </li> <li> Open issues: { repoData.open_issues_count } </li> </ul> </div> ); }); return ( <div> <h1>Fetched repo data</h1> <div className={ styles.data }> { repos } </div> </div> ); } }
app/javascript/mastodon/components/loading_indicator.js
RobertRence/Mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const LoadingIndicator = () => ( <div className='loading-indicator'> <div className='loading-indicator__figure' /> <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' /> </div> ); export default LoadingIndicator;
src/DatePicker/DatePicker.spec.js
w01fgang/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import DatePicker from './DatePicker'; import getMuiTheme from '../styles/getMuiTheme'; import TextField from '../TextField'; describe('<DatePicker />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); describe('formatDate', () => { it('should use the default format', () => { const date = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT const wrapper = shallowWithContext( <DatePicker value={date} /> ); assert.strictEqual(wrapper.find(TextField).props().value, '2015-12-01', 'should format the date to ISO 8601 (YYYY-MM-DD)'); }); }); });
draft-js-buttons/src/components/BlockquoteButton/index.js
koaninc/draft-js-plugins
import React from 'react'; import createBlockStyleButton from '../../utils/createBlockStyleButton'; export default createBlockStyleButton({ blockType: 'blockquote', children: ( <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"> <path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z" /> <path d="M0 0h24v24H0z" fill="none" /> </svg> ), });
client/src/components/ElementEditor/tests/ElementActions-test.js
dnadesign/silverstripe-elemental
/* eslint-disable import/no-extraneous-dependencies */ /* global jest, describe, it, expect */ import React from 'react'; import { Component as ElementActions } from '../ElementActions'; import Enzyme, { shallow } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import AbstractAction from 'components/ElementActions/AbstractAction'; Enzyme.configure({ adapter: new Adapter() }); describe('ElementActions', () => { const ActionMenuComponent = (props) => <div>{props.children}</div>; const testTabs = [ { title: 'Content', name: 'Main' }, { title: 'Settings', name: 'Settings' }, { title: 'History', name: 'History' } ]; const editTabsClick = () => {}; describe('renderEditTabs()', () => { it('should map input tabs into an array of buttons', () => { const wrapper = shallow( <ElementActions areaId={1} editTabs={testTabs} type={{ title: 'Some block' }} ActionMenuComponent={ActionMenuComponent} handleEditTabsClick={editTabsClick} /> ); const actions = wrapper.find(AbstractAction); expect(actions).toHaveLength(3); expect(actions.at(0).props().title).toEqual('Content'); expect(actions.at(1).props().title).toEqual('Settings'); expect(actions.at(2).props().title).toEqual('History'); }); }); describe('render()', () => { it('should render the given "edit tabs" in the action menu', () => { const wrapper = shallow( <ElementActions areaId={1} editTabs={testTabs} type={{ title: 'Some block' }} ActionMenuComponent={ActionMenuComponent} handleEditTabsClick={editTabsClick} /> ); // No dropdown separator should exist when there are no non-CMS actions expect(wrapper.find('DropdownItem').length).toBe(0); // See all the relevant action menu options expect(wrapper.html()).toContain('Content'); expect(wrapper.html()).toContain('Settings'); expect(wrapper.html()).toContain('History'); }); it('should render a divider when CMS tab actions and default actions are rendered', () => { const wrapper = shallow( <ElementActions areaId={1} editTabs={testTabs} type={{ title: 'Some block' }} ActionMenuComponent={ActionMenuComponent} handleEditTabsClick={editTabsClick} > <AbstractAction title="some button" /> </ElementActions> ); expect(wrapper.find('DropdownItem').length).toBe(1); }); }); });
src/components/video_list.js
lingyaomeng1/youtube-search
import React from 'react' import VideoListItem from './video_list_item' const VideoList = (props) => { const videoItems = props.videos.map((video) => { return ( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} /> ); }); return ( <ul className='col-md-4 list-group'> {videoItems} </ul> ); } export default VideoList;
src/components/NewArticle/PostList.js
chuntielin/Blog_Yeoman_Fullstack
import React from 'react'; import BlogActions from '../../actions/BlogActions'; import BlogStore from '../../stores/BlogStore'; // Components import PostItem from './PostItem'; const PostList = React.createClass({ getInitialState(){ return {articles: BlogStore.getAll()} }, _onChange(){ this.setState({articles: BlogStore.getAll()}) }, componentDidMount(){ BlogActions.fetch() BlogStore.addChangeListener(this._onChange) }, componentWillUnmount(){ BlogStore.removeChangeListener(this._onChange) }, render(){ return( <div> {this.state.articles.map((item) => { return <PostItem item={item} /> })} </div> ) } }); module.exports = PostList;
client/App/Members/Table/TableRow/index.js
JohannesAnd/SKWebsite
import React from 'react'; import { state, props, sequences } from 'cerebral'; import { connect } from '@cerebral/react'; import { faCheck, faPencilAlt, faTimes, } from '@fortawesome/free-solid-svg-icons'; import Mails from './Mails'; import Status from './Status'; import UserLanguage from 'common/UserLanguage'; import { TableRow, TableCell, Icon, IconClickable } from './elements'; export default connect( { member: state`profiles.${props`uid`}`, editing: state`members.edit.uid`, semester: state`members.edit.semester`, year: state`members.edit.year`, editMember: sequences`members.editMember`, updateMemberUntil: sequences`members.updateMemberUntil`, format: state`format`, }, function TableRowComponent({ className, member, editing, uid, editMember, updateMemberUntil, format, }) { const isEditing = editing === uid; return ( <UserLanguage> {t => ( <TableRow className={className}> <TableCell>{member.name}</TableCell> <TableCell>{member.email}</TableCell> <TableCell> <Mails uid={uid} /> </TableCell> <TableCell> {member.termsAccepted ? format(member.termsAccepted, 'Do MMM HH:mm') : '-'} </TableCell> <TableCell centered> {member.isAdmin && <Icon icon={faCheck} />} </TableCell> <TableCell> <Status uid={uid} /> </TableCell> <TableCell centered> {isEditing ? ( <React.Fragment> <IconClickable onClick={() => editMember({ uid: null })} icon={faTimes} /> <IconClickable onClick={() => updateMemberUntil()} icon={faCheck} /> </React.Fragment> ) : ( <IconClickable onClick={() => editMember({ uid })} icon={faPencilAlt} /> )} </TableCell> </TableRow> )} </UserLanguage> ); } );
src/library/Dialog/__tests__/DialogBody.spec.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import { shallow } from 'enzyme'; import Dialog from '../Dialog'; import DialogBody from '../DialogBody'; import examples from '../../../website/app/demos/Dialog/DialogBody/examples'; import testDemoExamples from '../../../../utils/testDemoExamples'; function shallowDialog(props = {}) { const dialogBodyProps = { ...props }; return shallow( <Dialog title="Title"> <DialogBody {...dialogBodyProps} /> </Dialog> ); } describe('DialogBody', () => { it('renders', () => { const dialog = shallowDialog(); expect(dialog.exists()).toEqual(true); }); testDemoExamples(examples); });
test/integration/basic/pages/nav/as-path.js
giacomorebonato/next.js
import React from 'react' export default class extends React.Component { static getInitialProps ({ asPath, req }) { return { asPath } } render () { return ( <div className='as-path-content'> {this.props.asPath} </div> ) } }
test/SafeAnchorSpec.js
chilts/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import SafeAnchor from '../src/SafeAnchor'; describe('SafeAnchor', function() { it('renders an anchor tag', function() { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />); const node = React.findDOMNode(instance); node.tagName.should.equal('A'); }); it('forwards arbitrary props to the anchor', function() { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor herpa='derpa' />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.herpa.should.equal('derpa'); }); it('forwards provided href', function() { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='http://google.com' />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.href.should.equal('http://google.com'); }); it('ensures that an href is provided', function() { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.href.should.equal(''); }); it('forwards onClick handler', function(done) { const handleClick = (event) => { done(); }; const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor onClick={handleClick} />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); ReactTestUtils.Simulate.click(anchor); }); it('prevents default when no href is provided', function(done) { const handleClick = (event) => { expect(event.isDefaultPrevented()).to.not.be.ok; setTimeout(() => { event.isDefaultPrevented().should.be.true; done(); }, 100); }; const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor onClick={handleClick} />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); ReactTestUtils.Simulate.click(anchor); }); it('does not prevent default when href is provided', function(done) { const handleClick = (event) => { expect(event.isDefaultPrevented()).to.not.be.ok; setTimeout(() => { expect(event.isDefaultPrevented()).to.not.be.ok; done(); }); }; const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='#' onClick={handleClick} />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); ReactTestUtils.Simulate.click(anchor); }); it('forwards provided role', function () { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor role='test' />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.role.should.equal('test'); }); it('forwards provided role with href', function () { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor role='test' href='http://google.com' />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.role.should.equal('test'); }); it('set role=button with no provided href', function () { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); anchor.props.role.should.equal('button'); }); it('sets no role with provided href', function () { const instance = ReactTestUtils.renderIntoDocument(<SafeAnchor href='http://google.com' />); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); expect(anchor.props.role).to.be.undefined; }); });
client/src/About.js
martchellop/shcode
import React, { Component } from 'react'; import file from './data/about.json'; class About extends Component { render(){ const text_st = { fontSize: "16px" }; return( <div className="text-center fluid"> <h1>{file.title}</h1> {file.pars.map( (par, idx) => { return(<p key={idx} style={text_st}>{par}</p>); })} </div> ); } } export default About;
src/Select.js
pedroseac/react-select
import React from 'react'; import ReactDOM from 'react-dom'; import Input from 'react-input-autosize'; import classNames from 'classnames'; import stripDiacritics from './utils/stripDiacritics'; import Async from './Async'; import Option from './Option'; import Value from './Value'; function stringifyValue (value) { if (typeof value === 'object') { return JSON.stringify(value); } else { return value; } } const Select = React.createClass({ statics: { Async }, displayName: 'Select', propTypes: { addLabelText: React.PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input allowCreate: React.PropTypes.bool, // whether to allow creation of new entries autofocus: React.PropTypes.bool, // autofocus the component on mount backspaceRemoves: React.PropTypes.bool, // whether backspace removes an item if there is no text input className: React.PropTypes.string, // className for the outer element clearAllText: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]), // title for the "clear" control when multi: true clearValueText: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]), // title for the "clear" control clearable: React.PropTypes.bool, // should it be possible to reset value delimiter: React.PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: React.PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: React.PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: React.PropTypes.func, // method to filter a single option (option, filterString) filterOptions: React.PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: React.PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering inputProps: React.PropTypes.object, // custom attributes for the Input isLoading: React.PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) labelKey: React.PropTypes.string, // path of the label value in option objects matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on scrollMenuIntoView: React.PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged menuBuffer: React.PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuStyle: React.PropTypes.object, // optional style to apply to the menu menuContainerStyle: React.PropTypes.object, // optional style to apply to the menu container multi: React.PropTypes.bool, // multi-value input name: React.PropTypes.string, // generates a hidden <input /> tag with this field name for html forms newOptionCreator: React.PropTypes.func, // factory to create new options when allowCreate set noResultsText: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]), // placeholder displayed when there are no matching search results onBlur: React.PropTypes.func, // onBlur handler: function (event) {} onChange: React.PropTypes.func, // onChange handler: function (newValue) {} onFocus: React.PropTypes.func, // onFocus handler: function (event) {} onInputChange: React.PropTypes.func, // onInputChange handler: function (inputValue) {} onValueClick: React.PropTypes.func, // onClick handler for value labels: function (value, event) {} onMenuScrollToBottom: React.PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options optionComponent: React.PropTypes.func, // option component to render in dropdown optionRenderer: React.PropTypes.func, // optionRenderer: function (option) {} options: React.PropTypes.array, // array of options placeholder: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.node ]), // field placeholder, displayed when there's no value searchable: React.PropTypes.bool, // whether to enable searching feature or not simpleValue: React.PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: React.PropTypes.object, // optional style to apply to the control tabIndex: React.PropTypes.string, // optional tab index of the control value: React.PropTypes.any, // initial field value valueComponent: React.PropTypes.func, // value component to render valueKey: React.PropTypes.string, // path of the label value in option objects valueRenderer: React.PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: React.PropTypes.object, // optional style to apply to the component wrapper }, getDefaultProps () { return { addLabelText: 'Add "{label}"?', allowCreate: false, backspaceRemoves: true, clearAllText: 'Clear all', clearValueText: 'Clear value', clearable: true, delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: true, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', scrollMenuIntoView: true, menuBuffer: 0, multi: false, noResultsText: 'No results found', optionComponent: Option, placeholder: 'Select...', searchable: true, simpleValue: false, valueComponent: Value, valueKey: 'value', }; }, getInitialState () { return { inputValue: '', isFocused: false, isLoading: false, isOpen: false, isPseudoFocused: false, }; }, componentDidMount () { if (this.props.autofocus) { this.focus(); } }, componentDidUpdate (prevProps, prevState) { if (prevState.inputValue !== this.state.inputValue && this.props.onInputChange) { this.props.onInputChange(this.state.inputValue); } if (this._scrollToFocusedOptionOnUpdate && this.refs.focused && this.refs.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = ReactDOM.findDOMNode(this.refs.focused); var menuDOM = ReactDOM.findDOMNode(this.refs.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = (focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight); } } if (this.props.scrollMenuIntoView && this.refs.menuContainer) { var menuContainerRect = this.refs.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollTo(0, window.scrollY + menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); } }, focus () { if (!this.refs.input) return; this.refs.input.focus(); }, handleMouseDown (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen, }); } if (this.state.isFocused) { // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false, }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow (event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, closeMenu () { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '', }); }, handleInputFocus (event) { var isOpen = this.state.isOpen || this._openAfterFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur (event) { if (this.refs.menu && document.activeElement.isEqualNode(this.refs.menu)) { return; } if (this.props.onBlur) { this.props.onBlur(event); } this.setState({ inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, }); }, handleInputChange (event) { this.setState({ isOpen: true, isPseudoFocused: false, inputValue: event.target.value, }); }, handleKeyDown (event) { if (this.props.disabled) return; switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen) { return; } this.selectFocusedOption(); break; case 13: // enter if (!this.state.isOpen) return; this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; // case 188: // , // if (this.props.allowCreate && this.props.multi) { // event.preventDefault(); // event.stopPropagation(); // this.selectFocusedOption(); // } else { // return; // } // break; default: return; } event.preventDefault(); }, handleValueClick (option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll (event) { if (!this.props.onMenuScrollToBottom) return; let { target } = event; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, getOptionLabel (op) { return op[this.props.labelKey]; }, getValueArray () { let value = this.props.value; if (this.props.multi) { if (typeof value === 'string') value = value.split(this.props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(this.expandValue).filter(i => i); } var expandedValue = this.expandValue(value); return expandedValue ? [expandedValue] : []; }, expandValue (value) { if (typeof value !== 'string' && typeof value !== 'number') return value; let { options, valueKey } = this.props; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue (value) { if (!this.props.onChange) return; if (this.props.simpleValue && value) { value = this.props.multi ? value.map(i => i[this.props.valueKey]).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue (value) { if (this.props.multi) { this.addValue(value); this.setState({ inputValue: '', }); } else { this.setValue(value); this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused, }); } }, addValue (value) { var valueArray = this.getValueArray(); this.setValue(valueArray.concat(value)); }, popValue () { var valueArray = this.getValueArray(); if (!valueArray.length) return; if (valueArray[valueArray.length-1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue (value) { var valueArray = this.getValueArray(); this.setValue(valueArray.filter(i => i !== value)); this.focus(); }, clearValue (event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(null); this.setState({ isOpen: false, inputValue: '', }, this.focus); }, focusOption (option) { this.setState({ focusedOption: option }); }, focusNextOption () { this.focusAdjacentOption('next'); }, focusPreviousOption () { this.focusAdjacentOption('previous'); }, focusAdjacentOption (dir) { var options = this._visibleOptions.filter(i => !i.disabled); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1] }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i]) { focusedIndex = i; break; } } var focusedOption = options[0]; if (dir === 'next' && focusedIndex > -1 && focusedIndex < options.length - 1) { focusedOption = options[focusedIndex + 1]; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedOption = options[focusedIndex - 1]; } else { focusedOption = options[options.length - 1]; } } this.setState({ focusedOption: focusedOption }); }, selectFocusedOption () { // if (this.props.allowCreate && !this.state.focusedOption) { // return this.selectValue(this.state.inputValue); // } if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading () { if (!this.props.isLoading) return; return ( <span className="Select-loading-zone" aria-hidden="true"> <span className="Select-loading" /> </span> ); }, renderValue (valueArray, isOpen) { let renderLabel = this.props.valueRenderer || this.getOptionLabel; let ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? <div className="Select-placeholder">{this.props.placeholder}</div> : null; } let onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map((value, i) => { return ( <ValueComponent disabled={this.props.disabled || value.clearableValue === false} key={`value-${i}-${value[this.props.valueKey]}`} onClick={onClick} onRemove={this.removeValue} value={value} > {renderLabel(value)} </ValueComponent> ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return ( <ValueComponent disabled={this.props.disabled} onClick={onClick} value={valueArray[0]} > {renderLabel(valueArray[0])} </ValueComponent> ); } }, renderInput (valueArray) { var className = classNames('Select-input', this.props.inputProps.className); if (this.props.disabled || !this.props.searchable) { return ( <div {...this.props.inputProps} className={className} tabIndex={this.props.tabIndex || 0} onBlur={this.handleInputBlur} onFocus={this.handleInputFocus} ref="input" style={{ border: 0, width: 1, display:'inline-block' }}/> ); } return ( <Input {...this.props.inputProps} className={className} tabIndex={this.props.tabIndex} onBlur={this.handleInputBlur} onChange={this.handleInputChange} onFocus={this.handleInputFocus} minWidth="5" ref="input" value={this.state.inputValue} /> ); }, renderClear () { if (!this.props.clearable || !this.props.value || (this.props.multi && !this.props.value.length) || this.props.disabled || this.props.isLoading) return; return ( <span className="Select-clear-zone" title={this.props.multi ? this.props.clearAllText : this.props.clearValueText} aria-label={this.props.multi ? this.props.clearAllText : this.props.clearValueText} onMouseDown={this.clearValue} onTouchEnd={this.clearValue}> <span className="Select-clear" dangerouslySetInnerHTML={{ __html: '&times;' }} /> </span> ); }, renderArrow () { return ( <span className="Select-arrow-zone" onMouseDown={this.handleMouseDownOnArrow}> <span className="Select-arrow" onMouseDown={this.handleMouseDownOnArrow} /> </span> ); }, filterOptions (excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (typeof this.props.filterOptions === 'function') { return this.props.filterOptions.call(this, options, filterValue, excludeOptions); } else if (this.props.filterOptions) { if (this.props.ignoreAccents) { filterValue = stripDiacritics(filterValue); } if (this.props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (excludeOptions) excludeOptions = excludeOptions.map(i => i[this.props.valueKey]); return options.filter(option => { if (excludeOptions && excludeOptions.indexOf(option[this.props.valueKey]) > -1) return false; if (this.props.filterOption) return this.props.filterOption.call(this, option, filterValue); if (!filterValue) return true; var valueTest = String(option[this.props.valueKey]); var labelTest = String(option[this.props.labelKey]); if (this.props.ignoreAccents) { if (this.props.matchProp !== 'label') valueTest = stripDiacritics(valueTest); if (this.props.matchProp !== 'value') labelTest = stripDiacritics(labelTest); } if (this.props.ignoreCase) { if (this.props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (this.props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return this.props.matchPos === 'start' ? ( (this.props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue) || (this.props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue) ) : ( (this.props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0) || (this.props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0) ); }); } else { return options; } }, renderMenu (options, valueArray, focusedOption) { if (options && options.length) { let Option = this.props.optionComponent; let renderLabel = this.props.optionRenderer || this.getOptionLabel; return options.map((option, i) => { let isSelected = valueArray && valueArray.indexOf(option) > -1; let isFocused = option === focusedOption; let optionRef = isFocused ? 'focused' : null; let optionClass = classNames({ 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled, }); return ( <Option className={optionClass} isDisabled={option.disabled} isFocused={isFocused} key={`option-${i}-${option[this.props.valueKey]}`} onSelect={this.selectValue} onFocus={this.focusOption} option={option} isSelected={isSelected} ref={optionRef} > {renderLabel(option)} </Option> ); }); } else { return ( <div className="Select-noresults"> {this.props.noResultsText} </div> ); } }, renderHiddenField (valueArray) { if (!this.props.name) return; let value = valueArray.map(i => stringifyValue(i[this.props.valueKey])).join(this.props.delimiter); return <input type="hidden" ref="value" name={this.props.name} value={value} disabled={this.props.disabled} />; }, getFocusableOption (selectedOption) { var options = this._visibleOptions; if (!options.length) return; let focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && options.indexOf(focusedOption) > -1) return focusedOption; for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return options[i]; } }, render () { let valueArray = this.getValueArray(); let options = this._visibleOptions = this.filterOptions(this.props.multi ? valueArray : null); let isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; let focusedOption = this._focusedOption = this.getFocusableOption(valueArray[0]); let className = classNames('Select', this.props.className, { 'Select--multi': this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length, }); return ( <div ref="wrapper" className={className} style={this.props.wrapperStyle}> {this.renderHiddenField(valueArray)} <div ref="control" className="Select-control" style={this.props.style} onKeyDown={this.handleKeyDown} onMouseDown={this.handleMouseDown} onTouchEnd={this.handleMouseDown}> {this.renderValue(valueArray, isOpen)} {this.renderInput(valueArray)} {this.renderLoading()} {this.renderClear()} {this.renderArrow()} </div> {isOpen ? ( <div ref="menuContainer" className="Select-menu-outer" style={this.props.menuContainerStyle}> <div ref="menu" className="Select-menu" style={this.props.menuStyle} onScroll={this.handleMenuScroll} onMouseDown={this.handleMouseDownOnMenu}> {this.renderMenu(options, !this.props.multi ? valueArray : null, focusedOption)} </div> </div> ) : null} </div> ); } }); export default Select;
app/components/1_Keymaps/Keymaps/EditKeymapModal.js
shug0/Awesomidi
import React, { Component } from 'react'; // MATERIAL import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; // Components import EditAvatar from './EditAvatar'; class EditKeymapModal extends Component { constructor() { super(); this.state = { open: true, openIconModal: false, name: '', command: '', keyID: '', iconClass: '', waitingInput: false, }; this.handleChangeName = this.handleChangeName.bind(this); this.handleChangeCommand = this.handleChangeCommand.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleDelete = this.handleDelete.bind(this); this.handleBindMidiKey = this.handleBindMidiKey.bind(this); this.handleError = this.handleError.bind(this); this.handleOpenIconModal = this.handleOpenIconModal.bind(this); this.handleCloseIconModal = this.handleCloseIconModal.bind(this); this.handleChangeIcon = this.handleChangeIcon.bind(this); } componentWillMount() { if (this.props.action === 'edit') { this.setState({ name: this.props.keymap.name, command: this.props.keymap.command, iconClass: this.props.keymap.iconClass, keyID: this.props.keymap.keyID, }); } } componentDidMount() { this.props.stopExecuteBindings(); } componentWillUnmount() { this.props.startExecuteBindings(); } componentWillReceiveProps(nextProps) { this.handleMidiEvent(nextProps); } handleMidiEvent(nextProps) { if (this.state.waitingInput && nextProps.events[nextProps.events.length-1].action === 'keyUp') { const redundancyKeymaps = this.props.keymaps.filter((keymap) => { return(keymap.keyID === nextProps.events[nextProps.events.length-1].key); }).length; if (redundancyKeymaps === 0) { this.setState({ waitingInput: false, keyID: nextProps.events[nextProps.events.length-1].key }); this.props.stopListeningEvents(); } else { this.handleError('This key is already used.') } } } handleBindMidiKey() { this.props.startListeningEvents(); this.setState({ waitingInput: true, keyID: '' }); } handleChangeName(event) { this.setState({ name: event.target.value, }); }; handleChangeCommand(event) { this.setState({ command: event.target.value, }); }; handleChangeIcon(icon) { this.setState({ iconClass: icon, openIconModal: false }); } handleError(error) { console.log(error); } handleDelete() { this.props.removeKeymap(this.props.index); this.props.closeDialog(); }; handleSubmit() { const newKeymap = { name: this.state.name, command: this.state.command, iconClass: this.state.iconClass, keyID: this.state.keyID }; this.props.action === 'edit' && this.props.index && this.props.editKeymap(this.props.index, newKeymap); this.props.action === 'add' && this.props.addKeymap(newKeymap); this.props.closeDialog(); }; handleOpenIconModal() { this.setState({ openIconModal: true }) } handleCloseIconModal() { this.setState({ openIconModal: false }) } render() { // If all the form are filled => true const formFilled = !( this.state.name.length > 2 && this.state.command.length > 2 && this.state.keyID !== null ); // Assigning text depending on the action let titleText; let principalButtonText; if (this.props.action === 'add') { titleText = 'Add a new keymap'; principalButtonText = 'Add'; } if (this.props.action === 'edit') { titleText = 'Edit keymap'; principalButtonText = 'Save'; } // Changing text on the binding midi button const labelBindingKeyButton = () => { if (this.state.keyID === '' && !this.state.waitingInput) return 'Bind MIDI Key'; if (this.state.keyID !== '' && !this.state.waitingInput) return 'Key : '+ this.state.keyID; if (this.state.waitingInput) return 'Press the key to assign...'; }; const actions = [ <FlatButton label="Delete" style={{float: 'left'}} secondary={true} onTouchTap={this.handleDelete} />, <FlatButton label="Cancel" onTouchTap={this.props.closeDialog} />, <FlatButton label={principalButtonText} primary={true} disabled={formFilled} onTouchTap={this.handleSubmit} />, ]; return ( <div> <Dialog title={titleText} actions={actions} modal={true} open={this.state.open} > <EditAvatar iconClass={this.state.iconClass} open={this.state.openIconModal} handleChangeIcon={this.handleChangeIcon} requestOpen={this.handleOpenIconModal} requestClose={this.handleCloseIconModal} /> <TextField floatingLabelText="Name" value={this.state.name} onChange={this.handleChangeName} style={{width: '100%'}} /> <TextField floatingLabelText="Command" value={this.state.command} onChange={this.handleChangeCommand} style={{width: '100%'}} /> <RaisedButton label={labelBindingKeyButton()} labelPosition="before" containerElement="label" onTouchTap={this.handleBindMidiKey} disableTouchRipple style={{ marginTop: '1em' }} /> </Dialog> </div> ); } } export default EditKeymapModal;
src/components/__tests__/horizontal-bar-content-test.js
ronlobo/building-os-charts
import Component from '../horizontal-bar-content'; import TestFunctions from './__test-functions__'; import React from 'react'; describe('HorizontalBarContent', () => { const { renderIntoDocument } = React.addons.TestUtils; TestFunctions.isOfExpectedType(Component, 'g', 'horizontal-bar-content'); TestFunctions.hasExpectedDefaultProps(Component, { height: 0, icon: '', iconClipPathId: '', iconHeight: 0, index: -1, label: '', width: 0, }); TestFunctions.hasExpectedInitialState(Component, { layout: {}, }); describe('has a componentWillReceiveProps method that', () => { const component = renderIntoDocument(<Component />); it('calls setStateFromProps', () => { spyOn(component, 'setStateFromProps'); component.componentWillReceiveProps({}); expect(component.setStateFromProps).toHaveBeenCalled(); }); }); describe('has a getLabelX method that', () => { const component = renderIntoDocument(<Component />); it('returns an x position for the label', () => { expect(component.getLabelX('', { children: [{ left: 10, }], })).toEqual(10); }); it('returns 0 for invalid input', () => { expect(component.getLabelX()).toEqual(0); expect(component.getLabelX('')).toEqual(0); expect(component.getLabelX('', {})).toEqual(0); expect(component.getLabelX('', { children: [], })).toEqual(0); expect(component.getLabelX()).toEqual(0); }); }); });
app/components/main/content/content/component.js
mic-fadeev/postglass
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import SpinnerComponent from '../../../base/spinner/component'; import HeadersComponent from '../headers/component'; import * as CurrentTableActions from '../../../../actions/currentTable'; import * as TablesActions from '../../../../actions/tables'; const propTypes = { tables: React.PropTypes.array.isRequired, items: React.PropTypes.array.isRequired, setCurrentTable: React.PropTypes.func.isRequired, getTableContent: React.PropTypes.func.isRequired, isFetching: React.PropTypes.bool.isRequired, titleTable: React.PropTypes.array.isRequired, }; class ContentComponent extends Component { componentWillReceiveProps(nextProps) { if (!this.props.tables.length && nextProps.tables.length) { let currentTable = window.localStorage.currentTable; if (currentTable) { let isFind = false; for (const table of nextProps.tables) { if (table.table_name === currentTable) { isFind = true; break; } } if (!isFind) { currentTable = nextProps.tables[0].table_name; } } else { currentTable = nextProps.tables[0].table_name; } this.props.setCurrentTable(currentTable); this.props.getTableContent({ tableName: currentTable }); } } render() { const { titleTable, items, isFetching } = this.props; return ( <div> { !isFetching && <div> <table className ="table table-bordered table-striped table-fixed"> <thead> <HeadersComponent titleTable = {titleTable} /> </thead> <tbody> { items.map((item, key) => { const fields = []; let keyA = 0; for (const header of titleTable) { keyA += 1; fields.push( <td className="truncate" key={keyA}>{item[header]}</td> ); } return ( <tr key={key}> {fields} </tr> ); }) } </tbody> </table> </div> } <SpinnerComponent isShow={isFetching} /> </div> ); } } ContentComponent.propTypes = propTypes; function mapStateToProps(state) { return { titleTable: state.currentTable.titleTable, items: state.currentTable.items, isFetching: state.currentTable.isFetching, tables: state.tables }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...TablesActions, ...CurrentTableActions }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(ContentComponent);
src/components/fileTree/folder.js
fmsouza/wcode
import React from 'react'; import Icon from '../icon'; import ItemFile from './file'; import Menu from './directoryMenu'; export default class ItemFolder extends React.Component { state = { collapsed: true, files: [], folders: [] }; get chevronName() { return (this.state.collapsed) ? 'chevron-right' : 'chevron-down'; } get folderName() { return (this.state.collapsed) ? 'folder' : 'folder-open'; } componentWillMount() { const { files, folders } = this.props; this.setState({ files, folders }); } componentWillReceiveProps({ files, folders }) { this.setState({ files, folders }); } onClick() { const { name, path, onClick } = this.props; const collapsed = !this.state.collapsed; this.setState({ collapsed }, () => onClick({ name, path, collapsed })); } onRightClick(e) { e.preventDefault(); this.refs.menu.toggle(e.clientX, e.clientY); } createElement(type) { const { path } = this.props; const { files } = this.state; files.push({ type, path }); this.setState({ files }); } renderFile = (item) => <ItemFile {...item} key={`${item.path}-${Math.random()}`} onClick={this.props.onClick} />; renderFolder = (item) => ( <ItemFolder {...item} key={`${item.path}-${Math.random()}`} onClick={this.props.onClick} onRenderChild={this.props.onRenderChild} ref={ref => this.props.onRenderChild(item.path, ref)} /> ); renderSubNodes = (files, folders) => ( <div className="subnodes" children={[].concat(folders.map(this.renderFolder)).concat(files.map(this.renderFile))} /> ); render() { const { collapsed, files, folders } = this.state; return ( <div className="ItemFolder"> <div className="node" onClick={() => this.onClick()} onContextMenu={(e) => this.onRightClick(e)}> <div className="title"> <Icon name={this.chevronName} className="icon" /> <Icon name={this.folderName} className="icon" /> {this.props.name} </div> </div> <Menu ref="menu" {...this.props} /> {!collapsed && this.renderSubNodes(files, folders)} </div> ); } }
src/routes/Home/components/HomeView.js
shuliang/ReactConventionDemo
import React from 'react' import DuckImage from '../assets/Duck.jpg' import './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> </div> ) export default HomeView
dashboard/index.js
vinnyhuang/fw-dev-dashboard
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/app.js'; import 'colors.css/css/colors.min.css'; import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/css/bootstrap-theme.css'; import 'react-grid-layout/css/styles.css'; import 'react-resizable/css/styles.css'; import './css/index.css'; ReactDOM.render( <App />, document.getElementById('root') );
node_modules/native-base/Components/Widgets/Badge.js
mk007sg/threeSeaShells
/* @flow */ 'use strict'; import React from 'react'; import {View} from 'react-native'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; import Text from './Text'; export default class BadgeNB extends NativeBaseComponent { propTypes: { style : React.PropTypes.object } prepareRootProps() { var type = { backgroundColor:this.props.primary ? this.getTheme().brandPrimary : this.props.success ? this.getTheme().brandSuccess : this.props.info ? this.getTheme().brandInfo : this.props.warning ? this.getTheme().brandWarning : this.props.danger ? this.getTheme().brandDanger : this.getTheme().badgeBg, padding: 3, paddingHorizontal: 10, alignSelf: 'flex-start', borderRadius: 13.5, height: 27 } var defaultProps = { style: type } return computeProps(this.props, defaultProps); } render() { return( <View {...this.prepareRootProps()}> <Text style={{ color: (this.props.textStyle && this.props.textStyle.color) ? this.props.textStyle.color : this.getTheme().badgeColor, fontSize: this.getTheme().fontSizeBase, lineHeight: this.getTheme().lineHeight-1, textAlign: 'center'}}>{this.props.children} </Text> </View> ); } }
node_modules/@material-ui/core/esm/Divider/Divider.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import { fade } from '../styles/colorManipulator'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { height: 1, margin: 0, // Reset browser default style. border: 'none', flexShrink: 0, backgroundColor: theme.palette.divider }, /* Styles applied to the root element if `absolute={true}`. */ absolute: { position: 'absolute', bottom: 0, left: 0, width: '100%' }, /* Styles applied to the root element if `variant="inset"`. */ inset: { marginLeft: 72 }, /* Styles applied to the root element if `light={true}`. */ light: { backgroundColor: fade(theme.palette.divider, 0.08) }, /* Styles applied to the root element if `variant="middle"`. */ middle: { marginLeft: theme.spacing(2), marginRight: theme.spacing(2) } }; }; var Divider = React.forwardRef(function Divider(props, ref) { var _props$absolute = props.absolute, absolute = _props$absolute === void 0 ? false : _props$absolute, classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'hr' : _props$component, _props$light = props.light, light = _props$light === void 0 ? false : _props$light, _props$variant = props.variant, variant = _props$variant === void 0 ? 'fullWidth' : _props$variant, other = _objectWithoutProperties(props, ["absolute", "classes", "className", "component", "light", "variant"]); if (Component === 'li' && !other.role) { other.role = 'separator'; } return React.createElement(Component, _extends({ className: clsx(classes.root, variant === 'inset' && classes.inset, variant === 'middle' && classes.middle, absolute && classes.absolute, light && classes.light, className), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Divider.propTypes = { /** * Absolutely position the element. */ absolute: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the divider will have a lighter color. */ light: PropTypes.bool, /** * The variant to use. */ variant: PropTypes.oneOf(['fullWidth', 'inset', 'middle']) } : void 0; export default withStyles(styles, { name: 'MuiDivider' })(Divider);
src/components/common/svg-icons/communication/phone.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhone = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); CommunicationPhone = pure(CommunicationPhone); CommunicationPhone.displayName = 'CommunicationPhone'; CommunicationPhone.muiName = 'SvgIcon'; export default CommunicationPhone;
actor-apps/app-web/src/app/components/Main.react.js
zomeelee/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import VisibilityActionCreators from '../actions/VisibilityActionCreators'; import FaviconActionCreators from 'actions/FaviconActionCreators'; import FaviconStore from 'stores/FaviconStore'; import ActivitySection from 'components/ActivitySection.react'; import SidebarSection from 'components/SidebarSection.react'; import ToolbarSection from 'components/ToolbarSection.react'; import DialogSection from 'components/DialogSection.react'; import Favicon from 'components/common/Favicon.react'; //import AppCacheStore from 'stores/AppCacheStore'; //import AppCacheUpdateModal from 'components/modals/AppCacheUpdate.react'; const visibilitychange = 'visibilitychange'; const onVisibilityChange = () => { if (!document.hidden) { VisibilityActionCreators.createAppVisible(); FaviconActionCreators.setDefaultFavicon(); } else { VisibilityActionCreators.createAppHidden(); } }; const getStateFromStores = () => { return { faviconPath: FaviconStore.getFaviconPath() }; }; class Main extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); document.addEventListener(visibilitychange, onVisibilityChange); FaviconStore.addChangeListener(this.onChange); if (!document.hidden) { VisibilityActionCreators.createAppVisible(); } } onChange = () => { this.setState(getStateFromStores()); } render() { //let appCacheUpdateModal; //if (this.state.isAppUpdateModalOpen) { // appCacheUpdateModal = <AppCacheUpdateModal/>; //} return ( <div className="app row"> <Favicon path={this.state.faviconPath}/> <SidebarSection/> <section className="main col-xs"> <ToolbarSection/> <DialogSection/> </section> <ActivitySection/> {/*appCacheUpdateModal*/} </div> ); } } export default requireAuth(Main);
src/incident.js
danriti/pagerduty-review
import moment from 'moment-timezone'; import React from 'react'; const TIMESTAMP_FORMAT = 'dddd YYYY/MM/DD LT zz'; export default class Incident { constructor(incident) { this.id = incident.id; this.number = incident.incident_number; this.key = incident.incident_key; this.created = incident.created_on; this.lastChange = incident.last_status_change_on; this.url = incident.html_url; } timeOpen() { let diff = moment(this.lastChange).diff(moment(this.created)); return moment.duration(diff).humanize(); } minutesOpen() { let diff = moment(this.lastChange).diff(moment(this.created)); return moment.duration(diff).asMinutes(); } idLink() { return <a href={this.url}>{this.number}</a>; } hipchatUrl() { var date = moment(this.created), href = `/hipchat/${date.format('YYYY/MM/DD')}`, text = date.tz('America/New_York').format(TIMESTAMP_FORMAT); return <a href={href}>{text}</a>; } isAfterHours() { let created = moment.utc(this.created), hour = created.hour(), min = created.minute(), dayOfWeek = created.day(), isWeekend, isAfter, isBefore; isWeekend = (dayOfWeek == 6) || (dayOfWeek == 0); isAfter = (hour == 22 && min >=30) || hour > 21; // after 530pm EST isBefore = hour < 13; // before 9am EST return isWeekend || (isAfter || isBefore); } createdTimestamp() { return Incident.formatTimestamp(this.created); } /** * intentially formatting of timestamps to EST due to team's operating * schedule. if someone has a good reason to change this, go ahead! */ static formatTimestamp(timestamp) { return moment(timestamp) .tz('America/New_York') .format(TIMESTAMP_FORMAT); } }
src/routes.js
bobrown101/phi-tau
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './containers/HomePage'; import AboutPage from './components/AboutPage.js'; import NotFound from './containers/NotFound'; import Rush from './containers/Rush'; import LaserTagHome from'./containers/LaserTagHome'; import LocalHistory from './containers/LocalHistory'; import NationalHistory from './containers/NationalHistory'; import ContactPage from './containers/Contact'; import Admin from './containers/Admin'; import Event from './containers/Admin/Event'; import Login from './containers/Login'; import Vote from './containers/Vote'; import Poll from './containers/Poll'; import {requireAuthentication} from './components/AuthenticatedComponent'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage}/> <Route path="about" component={AboutPage}/> <Route path="local-history" component={LocalHistory}/> <Route path="national-history" component={NationalHistory}/> <Route path="rush" component={Rush}/> <Route path="lasertag" component={LaserTagHome}/> <Route path="contact" component={ContactPage}/> <Route path="admin-dashboard" component={requireAuthentication(Admin)}/> <Route path="event/:eventID" component={requireAuthentication(Event)}/> <Route path="poll/:eventID/:pollID" component={requireAuthentication(Poll)} /> <Route path="login" component={Login}/> <Route path="vote" component={Vote}/> <Route path="*" component={NotFound}/> </Route> );
pootle/static/js/auth/components/AccountActivation.js
ta2-1/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import { PureRenderMixin } from 'react-addons-pure-render-mixin'; import AuthContent from './AuthContent'; const AccountActivation = React.createClass({ propTypes: { onClose: React.PropTypes.func.isRequired, signUpEmail: React.PropTypes.string, }, mixins: [PureRenderMixin], /* Layout */ render() { let emailLinkMsg; if (this.props.signUpEmail) { emailLinkMsg = interpolate( gettext( 'We have sent an email containing the special link to ' + '<span>%s</span>. Please check your spam folder if you do not see' + ' the email.' ), [this.props.signUpEmail] ); } else { emailLinkMsg = gettext( 'We have sent an email containing the special link to the address ' + 'used to register this account. Please check your spam folder if ' + 'you do not see the email.' ); } const activationWarningMsg = gettext('Your account needs activation.'); const instructionsMsg = gettext( 'Please follow that link to continue the account creation.' ); return ( <AuthContent> <div className="actions sign-up"> <p>{activationWarningMsg}</p> <p dangerouslySetInnerHTML={{ __html: emailLinkMsg }} /> <p>{instructionsMsg}</p> {this.props.signUpEmail && <div> <button className="btn btn-primary" onClick={this.props.onClose} > {gettext('Close')} </button> </div> } </div> </AuthContent> ); }, }); export default AccountActivation;
src/clincoded/static/components/provisional_curation.js
ClinGen/clincoded
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import _ from 'underscore'; import moment from 'moment'; import url from 'url'; import { curator_page, history_views, userMatch, queryKeyValue } from './globals'; import { RestMixin } from './rest'; import { Form, FormMixin, Input } from '../libs/bootstrap/form'; import { PanelGroup, Panel } from '../libs/bootstrap/panel'; import { ContextualHelp } from '../libs/bootstrap/contextual_help'; import { parseAndLogError } from './mixins'; import { ClassificationDefinition } from './provisional_classification/definition'; import CurationSnapshots from './provisional_classification/snapshots'; import { sortListByDate } from '../libs/helpers/sort'; import { getClassificationSavedDate } from '../libs/get_saved_date'; import { allowPublishGlobal } from '../libs/allow_publish'; import { isScoringForCurrentSOP } from '../libs/sop'; import { renderAnimalOnlyTag } from '../libs/render_classification_animal_only_tag'; import * as CuratorHistory from './curator_history'; import * as methods from './methods'; import * as curator from './curator'; const CurationMixin = curator.CurationMixin; const RecordHeader = curator.RecordHeader; const CurationPalette = curator.CurationPalette; var ProvisionalCuration = createReactClass({ mixins: [FormMixin, RestMixin, CurationMixin, CuratorHistory], contextTypes: { navigate: PropTypes.func, closeModal: PropTypes.func }, queryValues: {}, propTypes: { href: PropTypes.string, session: PropTypes.object, affiliation: PropTypes.object, demoVersion: PropTypes.bool }, getInitialState: function() { return { user: null, // login user uuid gdm: null, // current gdm object, must be null initially. provisional: {}, // login user's existing provisional object, must be null initially. //assessments: null, // list of all assessments, must be nul initially. totalScore: null, autoClassification: 'No Classification', alteredClassification: 'No Modification', replicatedOverTime: false, reasons: '', classificationStatus: 'In progress', classificationSnapshots: [], evidenceSummary: '', contradictingEvidence: { proband: false, caseControl: false, experimental: false }, resetAlteredClassification: false, scoreTableValues: { // variables for autosomal dominant data probandOtherVariantCount: 0, probandOtherVariantPoints: 0, probandOtherVariantPointsCounted: 0, probandNullVariantCount: 0, probandNullVariantPoints: 0, probandNullVariantPointsCounted: 0, variantDenovoCount: 0, variantDenovoPoints: 0, variantDenovoPointsCounted: 0, // variables for autosomal recessive data autosomalRecessivePointsCounted: 0, twoVariantsProvenCount: 0, twoVariantsProvenPoints: 0, twoVariantsNotProvenCount: 0, twoVariantsNotProvenPoints: 0, // variables for segregation data // segregationTotalPoints is actually the raw, unconverted score; segregationPointsCounted is calculated and displayed score segregationCountCandidate: 0, segregationCountExome: 0, segregationCountTotal: 0, segregationPointsCandidate: 0, segregationPointsExome: 0, segregationTotalPoints: 0, segregationPointsCounted: 0, // variables for case-control data caseControlCount: 0, caseControlPoints: 0, caseControlPointsCounted: 0, // variables for Experimental data functionalPointsCounted: 0, functionalAlterationPointsCounted: 0, modelsRescuePointsCounted: 0, biochemicalFunctionCount: 0, biochemicalFunctionPoints: 0, proteinInteractionsCount: 0, proteinInteractionsPoints: 0, expressionCount: 0, expressionPoints: 0, patientCellsCount: 0, patientCellsPoints: 0, nonPatientCellsCount: 0, nonPatientCellsPoints: 0, nonHumanModelCount: 0, nonHumanModelPoints: 0, cellCultureCount: 0, cellCulturePoints: 0, rescueHumanModelCount: 0, rescueHumanModelPoints: 0, rescueNonHumanModelCount: 0, rescueNonHumanModelPoints: 0, rescueCellCultureCount: 0, rescueCellCulturePoints: 0, rescuePatientCellsCount: 0, rescuePatientCellsPoints: 0, // variables for total counts geneticEvidenceTotalPoints: 0, experimentalEvidenceTotalPoints: 0 } }; }, /** * Method to get a list of snapshots of a classification, either provisioned or approved, * given the matching UUID of the classificaiton object. * Called only once in the componentDidMount() lifecycle method via the loadData() method. * @param {string} provisionalUuid - UUID of the saved classification object in a snapshot */ getClassificationSnaphots(provisionalUuid) { this.getRestData('/search/?type=snapshot&resourceId=' + provisionalUuid).then(result => { this.setState({classificationSnapshots: result['@graph']}); }).catch(err => { console.log('Classification Snapshots Fetch Error=: %o', err); }); }, loadData: function() { var gdmUuid = this.queryValues.gdmUuid; // get gdm from db. var uris = _.compact([ gdmUuid ? '/gdm/' + gdmUuid : '' // search for entire data set of the gdm ]); this.getRestDatas( uris ).then(datas => { var stateObj = {}; stateObj.user = this.props.session.user_properties.uuid; datas.forEach(function(data) { switch(data['@type'][0]) { case 'gdm': stateObj.gdm = data; break; default: break; } }); // Update the Curator Mixin OMIM state with the current GDM's OMIM ID. if (stateObj.gdm && stateObj.gdm.omimId) { this.setOmimIdState(stateObj.gdm.omimId); } // search for provisional owned by affiliation or login user if (stateObj.gdm.provisionalClassifications && stateObj.gdm.provisionalClassifications.length > 0) { for (let provisionalClassification of stateObj.gdm.provisionalClassifications) { let curatorAffiliation = this.props.affiliation; let affiliation = provisionalClassification.affiliation ? provisionalClassification.affiliation : null; let creator = provisionalClassification.submitted_by; if ((affiliation && curatorAffiliation && affiliation === curatorAffiliation.affiliation_id) || (!affiliation && !curatorAffiliation && creator.uuid === stateObj.user)) { stateObj.provisional = provisionalClassification; stateObj.alteredClassification = stateObj.provisional.alteredClassification; stateObj.replicatedOverTime = stateObj.provisional.replicatedOverTime; stateObj.reasons = stateObj.provisional.reasons; stateObj.classificationStatus = stateObj.provisional.hasOwnProperty('classificationStatus') ? stateObj.provisional.classificationStatus : 'In progress', stateObj.evidenceSummary = stateObj.provisional.hasOwnProperty('evidenceSummary') ? stateObj.provisional.evidenceSummary : ''; } } } stateObj.previousUrl = url; this.setState(stateObj); if (stateObj.provisional && stateObj.provisional.uuid) { this.getClassificationSnaphots(stateObj.provisional.uuid); } return Promise.resolve(); }).then(result => { // once we have the GDM info, calculate the values for the score table this.calculateScoreTable(); }).catch(function(e) { console.log('OBJECT LOAD ERROR: %s — %s', e.statusText, e.url); }); }, componentDidMount: function() { this.loadData(); }, componentDidUpdate(prevProps, prevState) { // Need to delay the function call until the DOM is rendered // Only do invoke this call when the referrer is the classification view-only page const referrer = queryKeyValue('referrer', this.props.href); if (referrer && referrer.indexOf('classification-view') > -1) { setTimeout(this.scrollElementIntoView, 500); } // Highlight the modified classification dropdown menu and // its explanation text field if there is a svaed classifition if (Object.keys(this.state.provisional).length) { const alteredClassificationMenu = document.querySelector('.altered-classification select'); const alteredClassificationReasonField = document.querySelector('.altered-classification-reasons textarea'); if (alteredClassificationMenu) { alteredClassificationMenu.classList.add('form-control-info'); } if (alteredClassificationReasonField && this.state.reasons) { alteredClassificationReasonField.classList.add('form-control-info'); } } }, componentWillUnmount() { this.setState({resetAlteredClassification: false}); }, /** * Method to show the saved classification data in viewport */ scrollElementIntoView() { const element = document.querySelector('#classification-view'); if (element) { element.scrollIntoView(); } }, submitForm: function(e) { // Don't run through HTML submit handler e.preventDefault(); e.stopPropagation(); // Save all form values from the DOM. this.saveAllFormValues(); if (this.validateDefault()) { var calculate = queryKeyValue('calculate', this.props.href); var edit = queryKeyValue('edit', this.props.href); var newProvisional = this.state.provisional.uuid ? curator.flatten(this.state.provisional) : {}; newProvisional.autoClassification = this.state.autoClassification; newProvisional.alteredClassification = this.state.alteredClassification; newProvisional.reasons = this.state.reasons; newProvisional.replicatedOverTime = this.state.replicatedOverTime; newProvisional.contradictingEvidence = this.state.contradictingEvidence; newProvisional.classificationStatus = 'In progress'; newProvisional.classificationDate = moment().toISOString(); newProvisional.provisionedClassification = false; if (newProvisional.provisionalSubmitter) delete newProvisional.provisionalSubmitter; if (newProvisional.provisionalDate) delete newProvisional.provisionalDate; if (newProvisional.provisionalReviewDate) delete newProvisional.provisionalReviewDate; if (newProvisional.provisionalComment) delete newProvisional.provisionalComment; newProvisional.approvedClassification = false; if (newProvisional.approvalSubmitter) delete newProvisional.approvalSubmitter; if (newProvisional.classificationApprover) delete newProvisional.classificationApprover; if (newProvisional.classificationContributors) delete newProvisional.classificationContributors; if (newProvisional.additionalApprover) delete newProvisional.additionalApprover; if (newProvisional.approvalDate) delete newProvisional.approvalDate; if (newProvisional.approvalReviewDate) delete newProvisional.approvalReviewDate; if (newProvisional.approvalComment) delete newProvisional.approvalComment; if (newProvisional.contributorComment) delete newProvisional.contributorComment; newProvisional.sopVersion = ''; newProvisional.publishClassification = false; if (newProvisional.publishSubmitter) delete newProvisional.publishSubmitter; if (newProvisional.publishAffiliation) delete newProvisional.publishAffiliation; if (newProvisional.publishDate) delete newProvisional.publishDate; if (newProvisional.publishComment) delete newProvisional.publishComment; newProvisional.evidenceSummary = this.state.evidenceSummary; // Total points and points counted for all evidence let classificationPoints = {}, scoreTableValues = this.state.scoreTableValues; // Autosomal Dominant OR X-linked Disorder case-level evidence classificationPoints['autosomalDominantOrXlinkedDisorder'] = {}; // Proband with other variant type with some evidence of gene impact case information type classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithOtherVariantTypeWithGeneImpact'] = {}; classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithOtherVariantTypeWithGeneImpact']['evidenceCount'] = Number(scoreTableValues.probandOtherVariantCount); classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithOtherVariantTypeWithGeneImpact']['totalPointsGiven'] = Number(scoreTableValues.probandOtherVariantPoints); classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithOtherVariantTypeWithGeneImpact']['pointsCounted'] = Number(scoreTableValues.probandOtherVariantPointsCounted); // Proband with predicted or proven null variant case information type classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithPredictedOrProvenNullVariant'] = {}; classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithPredictedOrProvenNullVariant']['evidenceCount'] = Number(scoreTableValues.probandNullVariantCount); classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithPredictedOrProvenNullVariant']['totalPointsGiven'] = Number(scoreTableValues.probandNullVariantPoints); classificationPoints['autosomalDominantOrXlinkedDisorder']['probandWithPredictedOrProvenNullVariant']['pointsCounted'] = Number(scoreTableValues.probandNullVariantPointsCounted); // Variant is de novo case information type classificationPoints['autosomalDominantOrXlinkedDisorder']['variantIsDeNovo'] = {}; classificationPoints['autosomalDominantOrXlinkedDisorder']['variantIsDeNovo']['evidenceCount'] = Number(scoreTableValues.variantDenovoCount); classificationPoints['autosomalDominantOrXlinkedDisorder']['variantIsDeNovo']['totalPointsGiven'] = Number(scoreTableValues.variantDenovoPoints); classificationPoints['autosomalDominantOrXlinkedDisorder']['variantIsDeNovo']['pointsCounted'] = Number(scoreTableValues.variantDenovoPointsCounted); // Autosomal Recessive Disorder case-level evidence classificationPoints['autosomalRecessiveDisorder'] = {}; // Two variants (not predicted/proven null) with some evidence of gene impact in trans case information type classificationPoints['autosomalRecessiveDisorder']['twoVariantsWithGeneImpactInTrans'] = {}; classificationPoints['autosomalRecessiveDisorder']['twoVariantsWithGeneImpactInTrans']['evidenceCount'] = Number(scoreTableValues.twoVariantsNotProvenCount); classificationPoints['autosomalRecessiveDisorder']['twoVariantsWithGeneImpactInTrans']['totalPointsGiven'] = Number(scoreTableValues.twoVariantsNotProvenPoints); // Two variants in trans and at least one de novo or a predicted/proven null variant case information type classificationPoints['autosomalRecessiveDisorder']['twoVariantsInTransWithOneDeNovo'] = {}; classificationPoints['autosomalRecessiveDisorder']['twoVariantsInTransWithOneDeNovo']['evidenceCount'] = Number(scoreTableValues.twoVariantsProvenCount); classificationPoints['autosomalRecessiveDisorder']['twoVariantsInTransWithOneDeNovo']['totalPointsGiven'] = Number(scoreTableValues.twoVariantsProvenPoints); // Points counted for Autosomal Recessive Disorder case-level evidence classificationPoints['autosomalRecessiveDisorder']['pointsCounted'] = Number(scoreTableValues.autosomalRecessivePointsCounted); // Segregation case-level evidence classificationPoints['segregation'] = {}; classificationPoints['segregation']['evidenceCountCandidate'] = Number(scoreTableValues.segregationCountCandidate); classificationPoints['segregation']['evidenceCountExome'] = Number(scoreTableValues.segregationCountExome); classificationPoints['segregation']['evidenceCountTotal'] = Number(scoreTableValues.segregationCountTotal); classificationPoints['segregation']['evidencePointsCandidate'] = this.classificationMathRound(Number(scoreTableValues.segregationPointsCandidate), 2); classificationPoints['segregation']['evidencePointsExome'] = this.classificationMathRound(Number(scoreTableValues.segregationPointsExome), 2); classificationPoints['segregation']['totalPointsGiven'] = this.classificationMathRound(Number(scoreTableValues.segregationTotalPoints), 2); classificationPoints['segregation']['pointsCounted'] = Number(scoreTableValues.segregationPointsCounted); // Case-Control genetic evidence classificationPoints['caseControl'] = {}; classificationPoints['caseControl']['evidenceCount'] = Number(scoreTableValues.caseControlCount); classificationPoints['caseControl']['totalPointsGiven'] = Number(scoreTableValues.caseControlPoints); classificationPoints['caseControl']['pointsCounted'] = Number(scoreTableValues.caseControlPointsCounted); // Total points counted for all genetic evidence classificationPoints['geneticEvidenceTotal'] = Number(scoreTableValues.geneticEvidenceTotalPoints); // Function experimental evidence classificationPoints['function'] = {}; classificationPoints['function']['biochemicalFunctions'] = {}; classificationPoints['function']['biochemicalFunctions']['evidenceCount'] = Number(scoreTableValues.biochemicalFunctionCount); classificationPoints['function']['biochemicalFunctions']['totalPointsGiven'] = Number(scoreTableValues.biochemicalFunctionPoints); classificationPoints['function']['proteinInteractions'] = {}; classificationPoints['function']['proteinInteractions']['evidenceCount'] = Number(scoreTableValues.proteinInteractionsCount); classificationPoints['function']['proteinInteractions']['totalPointsGiven'] = Number(scoreTableValues.proteinInteractionsPoints); classificationPoints['function']['expression'] = {}; classificationPoints['function']['expression']['evidenceCount'] = Number(scoreTableValues.expressionCount); classificationPoints['function']['expression']['totalPointsGiven'] = Number(scoreTableValues.expressionPoints); classificationPoints['function']['totalPointsGiven'] = Number(scoreTableValues.biochemicalFunctionPoints) + Number(scoreTableValues.proteinInteractionsPoints) + Number(scoreTableValues.expressionPoints); classificationPoints['function']['pointsCounted'] = Number(scoreTableValues.functionalPointsCounted); // Functional Alteration experimental evidence classificationPoints['functionalAlteration'] = {}; classificationPoints['functionalAlteration']['patientCells'] = {}; classificationPoints['functionalAlteration']['patientCells']['evidenceCount'] = Number(scoreTableValues.patientCellsCount); classificationPoints['functionalAlteration']['patientCells']['totalPointsGiven'] = Number(scoreTableValues.patientCellsPoints); classificationPoints['functionalAlteration']['nonPatientCells'] = {}; classificationPoints['functionalAlteration']['nonPatientCells']['evidenceCount'] = Number(scoreTableValues.nonPatientCellsCount); classificationPoints['functionalAlteration']['nonPatientCells']['totalPointsGiven'] = Number(scoreTableValues.nonPatientCellsPoints); classificationPoints['functionalAlteration']['totalPointsGiven'] = Number(scoreTableValues.patientCellsPoints) + Number(scoreTableValues.nonPatientCellsPoints); classificationPoints['functionalAlteration']['pointsCounted'] = Number(scoreTableValues.functionalAlterationPointsCounted); // Model Systems and Rescue experimental evidence classificationPoints['modelsRescue'] = {}; classificationPoints['modelsRescue']['modelsNonHuman'] = {}; classificationPoints['modelsRescue']['modelsNonHuman']['evidenceCount'] = Number(scoreTableValues.nonHumanModelCount); classificationPoints['modelsRescue']['modelsNonHuman']['totalPointsGiven'] = Number(scoreTableValues.nonHumanModelPoints); classificationPoints['modelsRescue']['modelsCellCulture'] = {}; classificationPoints['modelsRescue']['modelsCellCulture']['evidenceCount'] = Number(scoreTableValues.cellCultureCount); classificationPoints['modelsRescue']['modelsCellCulture']['totalPointsGiven'] = Number(scoreTableValues.cellCulturePoints); classificationPoints['modelsRescue']['rescueHuman'] = {}; classificationPoints['modelsRescue']['rescueHuman']['evidenceCount'] = Number(scoreTableValues.rescueHumanModelCount); classificationPoints['modelsRescue']['rescueHuman']['totalPointsGiven'] = Number(scoreTableValues.rescueHumanModelPoints); classificationPoints['modelsRescue']['rescueNonHuman'] = {}; classificationPoints['modelsRescue']['rescueNonHuman']['evidenceCount'] = Number(scoreTableValues.rescueNonHumanModelCount); classificationPoints['modelsRescue']['rescueNonHuman']['totalPointsGiven'] = Number(scoreTableValues.rescueNonHumanModelPoints); classificationPoints['modelsRescue']['rescueCellCulture'] = {}; classificationPoints['modelsRescue']['rescueCellCulture']['evidenceCount'] = Number(scoreTableValues.rescueCellCultureCount); classificationPoints['modelsRescue']['rescueCellCulture']['totalPointsGiven'] = Number(scoreTableValues.rescueCellCulturePoints); classificationPoints['modelsRescue']['rescuePatientCells'] = {}; classificationPoints['modelsRescue']['rescuePatientCells']['evidenceCount'] = Number(scoreTableValues.rescuePatientCellsCount); classificationPoints['modelsRescue']['rescuePatientCells']['totalPointsGiven'] = Number(scoreTableValues.rescuePatientCellsPoints); classificationPoints['modelsRescue']['totalPointsGiven'] = Number(scoreTableValues.nonHumanModelPoints) + Number(scoreTableValues.cellCulturePoints) + Number(scoreTableValues.rescueHumanModelPoints) + Number(scoreTableValues.rescueNonHumanModelPoints) + Number(scoreTableValues.rescueCellCulturePoints) + Number(scoreTableValues.rescuePatientCellsPoints); classificationPoints['modelsRescue']['pointsCounted'] = Number(scoreTableValues.modelsRescuePointsCounted); // Total points counted for all experimental evidence classificationPoints['experimentalEvidenceTotal'] = Number(scoreTableValues.experimentalEvidenceTotalPoints); // TOTAL POINTS COUNTED FOR ALL EVIDENCE classificationPoints['evidencePointsTotal'] = Number(this.state.totalScore); // Assign 'classificationPoints' object to 'newProvisional' newProvisional.classificationPoints = Object.assign({}, classificationPoints); // Add affiliation if the user is associated with an affiliation // and if the data object has no affiliation if (this.props.affiliation && Object.keys(this.props.affiliation).length) { if (!newProvisional.affiliation) { newProvisional.affiliation = this.props.affiliation.affiliation_id; } } // check required item (reasons) var formErr = false; if (!newProvisional.reasons && newProvisional.alteredClassification !== 'No Modification') { formErr = true; this.setFormErrors('reasons', 'Required when changing classification.'); } if (newProvisional.autoClassification === newProvisional.alteredClassification) { formErr = true; this.setFormErrors('alteredClassification', 'Modified classification should be different from calculated classification'); } if (!formErr) { var backUrl = '/curation-central/?gdm=' + this.state.gdm.uuid; backUrl += this.queryValues.pmid ? '&pmid=' + this.queryValues.pmid : ''; if (this.state.provisional.uuid) { // edit existing provisional this.putRestData('/provisional/' + this.state.provisional.uuid, newProvisional).then(data => { var provisionalClassification = data['@graph'][0]; // Record provisional classification history var meta = { provisionalClassification: { gdm: this.state.gdm['@id'], alteredClassification: provisionalClassification.alteredClassification } }; this.recordHistory('modify', provisionalClassification, meta); this.resetAllFormValues(); window.location.href = '/provisional-classification/?gdm=' + this.state.gdm.uuid; }).catch(function(e) { console.log('PROVISIONAL GENERATION ERROR = : %o', e); }); } else { // save a new calculation and provisional classification this.postRestData('/provisional/', newProvisional).then(data => { return data['@graph'][0]; }).then(savedProvisional => { // Record provisional classification history var meta = { provisionalClassification: { gdm: this.state.gdm['@id'], alteredClassification: savedProvisional.alteredClassification } }; this.recordHistory('add', savedProvisional, meta); var theGdm = curator.flatten(this.state.gdm); if (theGdm.provisionalClassifications) { theGdm.provisionalClassifications.push(savedProvisional['@id']); } else { theGdm.provisionalClassifications = [savedProvisional['@id']]; } return this.putRestData('/gdm/' + this.state.gdm.uuid, theGdm).then(data => { return data['@graph'][0]; }); }).then(savedGdm => { this.resetAllFormValues(); window.location.href = '/provisional-classification/?gdm=' + this.state.gdm.uuid; }).catch(function(e) { console.log('PROVISIONAL GENERATION ERROR = %o', e); }); } } } }, cancelForm: function(e) { // Changed modal cancel button from a form input to a html button // as to avoid accepting enter/return key as a click event. // Removed hack in this method. window.history.go(-1); }, handleChange: function(ref, e) { if (ref === 'alteredClassification') { this.setState({ alteredClassification: this.refs[ref].getValue(), resetAlteredClassification: false }, () => { // Remove highlighting of modified classification selection dropdown menu // when the selected option is changed document.querySelector('.altered-classification select').classList.remove('form-control-info'); }); } else if (ref === 'reasons') { this.setState({reasons: this.refs[ref].getValue()}, () => { // Remove highlighting of modified classification selection dropdown menu // when the selected option is changed document.querySelector('.altered-classification-reasons textarea').classList.remove('form-control-info'); }); } else if (ref === 'classification-evidence-summary') { this.setState({evidenceSummary: this.refs[ref].getValue()}); } }, handleReplicatedOverTime: function() { let replicatedOverTime = this.state.replicatedOverTime; if (!replicatedOverTime) { replicatedOverTime = true; } else { replicatedOverTime = false; } this.setState({replicatedOverTime: replicatedOverTime}, this.calculateClassifications(this.state.totalScore, this.state.scoreTableValues['geneticEvidenceTotalPoints'], this.state.contradictingEvidence, replicatedOverTime)); }, familyScraper: function(user, families, annotation, segregationCountCandidate, segregationCountExome, segregationPointsCandidate, segregationPointsExome, individualMatched) { // function for looping through family (of GDM or of group) and finding all relevent information needed for score calculations // returns dictionary of relevant items that need to be updated within NewCalculation() families.forEach(family => { // get segregation of family, but only if it was made by user (may change later - MC) let curatorAffiliation = this.props.affiliation; if ((family.affiliation && curatorAffiliation && family.segregation && family.affiliation === curatorAffiliation.affiliation_id) || (!family.affiliation && !curatorAffiliation && family.segregation && family.submitted_by.uuid === user)) { // get lod score of segregation of family if (family.segregation.includeLodScoreInAggregateCalculation) { if ("lodPublished" in family.segregation && family.segregation.lodPublished === true && family.segregation.publishedLodScore) { if (family.segregation.sequencingMethod === 'Candidate gene sequencing') { segregationCountCandidate += 1; segregationPointsCandidate += family.segregation.publishedLodScore; } else if (family.segregation.sequencingMethod === 'Exome/genome or all genes sequenced in linkage region') { segregationCountExome += 1; segregationPointsExome += family.segregation.publishedLodScore; } } else if ("lodPublished" in family.segregation && family.segregation.lodPublished === false && family.segregation.estimatedLodScore) { if (family.segregation.sequencingMethod === 'Candidate gene sequencing') { segregationCountCandidate += 1; segregationPointsCandidate += family.segregation.estimatedLodScore; } else if (family.segregation.sequencingMethod === 'Exome/genome or all genes sequenced in linkage region') { segregationCountExome += 1; segregationPointsExome += family.segregation.estimatedLodScore; } } } } // get proband individuals of family if (family.individualIncluded && family.individualIncluded.length) { individualMatched = this.individualScraper(family.individualIncluded, individualMatched); } }); return { segregationCountCandidate: segregationCountCandidate, segregationCountExome: segregationCountExome, segregationPointsCandidate: segregationPointsCandidate, segregationPointsExome: segregationPointsExome, individualMatched: individualMatched }; }, individualScraper: function(individuals, individualMatched) { if (individuals) { individuals.forEach(individual => { if (individual.proband === true && (individual.scores && individual.scores.length)) { individualMatched.push(individual); } }); } return individualMatched; }, calculateScoreTable: function() { // Generate a new summary for url ../provisional-curation/?gdm=GDMId&calculate=yes // Calculation rules are defined by Small GCWG. See ClinGen_Interface_4_2015.pptx and Clinical Validity Classifications for detail let gdm = this.state.gdm; let scoreTableValues = this.state.scoreTableValues; let contradictingEvidence = this.state.contradictingEvidence; let curatorAffiliation = this.props.affiliation; const MAX_SCORE_CONSTANTS = { VARIANT_IS_DE_NOVO: 12, PREDICTED_OR_PROVEN_NULL_VARIANT: 10, OTHER_VARIANT_TYPE_WITH_GENE_IMPACT: 7, AUTOSOMAL_RECESSIVE: 12, SEGREGATION: 3, CASE_CONTROL: 12, FUNCTIONAL: 2, FUNCTIONAL_ALTERATION: 2, MODELS_RESCUE: 4, GENETIC_EVIDENCE: 12, EXPERIMENTAL_EVIDENCE: 6, TOTAL: 18 }; /*****************************************************/ /* Find all proband individuals that had been scored */ /*****************************************************/ let probandTotal = []; // all probands var proband_variants = []; let tempFamilyScraperValues = {}; let caseControlTotal = []; // scan gdm let annotations = gdm.annotations && gdm.annotations.length ? gdm.annotations : []; annotations.forEach(annotation => { let groups, families, individuals, experimentals; let individualMatched = []; // loop through groups groups = annotation.groups && annotation.groups.length ? annotation.groups : []; groups.forEach(group => { // loop through families using FamilyScraper families = group.familyIncluded && group.familyIncluded.length ? group.familyIncluded : []; tempFamilyScraperValues = this.familyScraper(this.state.user, families, annotation, scoreTableValues['segregationCountCandidate'], scoreTableValues['segregationCountExome'], scoreTableValues['segregationPointsCandidate'], scoreTableValues['segregationPointsExome'], individualMatched); scoreTableValues['segregationCountCandidate'] = tempFamilyScraperValues['segregationCountCandidate']; scoreTableValues['segregationCountExome'] = tempFamilyScraperValues['segregationCountExome']; scoreTableValues['segregationPointsCandidate'] = tempFamilyScraperValues['segregationPointsCandidate']; scoreTableValues['segregationPointsExome'] = tempFamilyScraperValues['segregationPointsExome']; individualMatched = tempFamilyScraperValues['individualMatched']; // get proband individuals of group if (group.individualIncluded && group.individualIncluded.length) { individualMatched = this.individualScraper(group.individualIncluded, individualMatched); } }); // loop through families using FamilyScraper families = annotation.families && annotation.families.length ? annotation.families : []; tempFamilyScraperValues = this.familyScraper(this.state.user, families, annotation, scoreTableValues['segregationCountCandidate'], scoreTableValues['segregationCountExome'], scoreTableValues['segregationPointsCandidate'], scoreTableValues['segregationPointsExome'], individualMatched); scoreTableValues['segregationCountCandidate'] = tempFamilyScraperValues['segregationCountCandidate']; scoreTableValues['segregationCountExome'] = tempFamilyScraperValues['segregationCountExome']; scoreTableValues['segregationPointsCandidate'] = tempFamilyScraperValues['segregationPointsCandidate']; scoreTableValues['segregationPointsExome'] = tempFamilyScraperValues['segregationPointsExome']; individualMatched = tempFamilyScraperValues['individualMatched']; // push all matched individuals from families and families of groups to probandTotal individualMatched.forEach(item => { probandTotal.push(item); }); // loop through individuals if (annotation.individuals && annotation.individuals.length) { // get proband individuals individualMatched = []; individualMatched = this.individualScraper(annotation.individuals, individualMatched); // push all matched individuals to probandTotal individualMatched.forEach(item => { probandTotal.push(item); }); } // loop through case-controls let caseControlMatched = []; if (annotation.caseControlStudies && annotation.caseControlStudies.length) { annotation.caseControlStudies.forEach(caseControl => { if (caseControl.scores && caseControl.scores.length) { caseControl.scores.forEach(score => { if ((score.affiliation && curatorAffiliation && score.affiliation === curatorAffiliation.affiliation_id) || (!score.affiliation && !curatorAffiliation && score.submitted_by.uuid === this.state.user)) { if ('score' in score && score.score !== 'none') { scoreTableValues['caseControlCount'] += 1; scoreTableValues['caseControlPoints'] += parseFloat(score.score); } } }); } }); } // loop through experimentals experimentals = annotation.experimentalData && annotation.experimentalData.length ? annotation.experimentalData : []; experimentals.forEach(experimental => { // loop through scores, if any if (experimental.scores && experimental.scores.length) { experimental.scores.forEach(score => { // only care about scores made by current user if ((score.affiliation && curatorAffiliation && score.affiliation === curatorAffiliation.affiliation_id) || (!score.affiliation && !curatorAffiliation && score.submitted_by.uuid === this.state.user)) { if (score.scoreStatus === 'Score') { // parse score of experimental let experimentalScore = 0; if ('score' in score && score.score !== 'none') { experimentalScore = parseFloat(score.score); // Use the score selected by curator (if any) } else if ('calculatedScore' in score && score.calculatedScore !== 'none') { experimentalScore = parseFloat(score.calculatedScore); // Otherwise, use default score (if any) } // assign score to correct sub-type depending on experiment type and other variables if (experimental.evidenceType && experimental.evidenceType === 'Biochemical Function') { scoreTableValues['biochemicalFunctionCount'] += 1; scoreTableValues['biochemicalFunctionPoints'] += experimentalScore; } else if (experimental.evidenceType && experimental.evidenceType === 'Protein Interactions') { scoreTableValues['proteinInteractionsCount'] += 1; scoreTableValues['proteinInteractionsPoints'] += experimentalScore; } else if (experimental.evidenceType && experimental.evidenceType === 'Expression') { scoreTableValues['expressionCount'] += 1; scoreTableValues['expressionPoints'] += experimentalScore; } else if (experimental.evidenceType && experimental.evidenceType === 'Functional Alteration') { if (experimental.functionalAlteration.functionalAlterationType && experimental.functionalAlteration.functionalAlterationType === 'Patient cells') { scoreTableValues['patientCellsCount'] += 1; scoreTableValues['patientCellsPoints'] += experimentalScore; } else if (experimental.functionalAlteration.functionalAlterationType && experimental.functionalAlteration.functionalAlterationType === 'Non-patient cells') { scoreTableValues['nonPatientCellsCount'] += 1; scoreTableValues['nonPatientCellsPoints'] += experimentalScore; } } else if (experimental.evidenceType && experimental.evidenceType === 'Model Systems') { if (experimental.modelSystems.modelSystemsType && experimental.modelSystems.modelSystemsType === 'Non-human model organism') { scoreTableValues['nonHumanModelCount'] += 1; scoreTableValues['nonHumanModelPoints'] += experimentalScore; } else if (experimental.modelSystems.modelSystemsType && experimental.modelSystems.modelSystemsType === 'Cell culture model') { scoreTableValues['cellCultureCount'] += 1; scoreTableValues['cellCulturePoints'] += experimentalScore; } } else if (experimental.evidenceType && experimental.evidenceType === 'Rescue') { if (experimental.rescue.rescueType && experimental.rescue.rescueType === 'Human') { scoreTableValues['rescueHumanModelCount'] += 1; scoreTableValues['rescueHumanModelPoints'] += experimentalScore; } else if (experimental.rescue.rescueType && experimental.rescue.rescueType === 'Non-human model organism') { scoreTableValues['rescueNonHumanModelCount'] += 1; scoreTableValues['rescueNonHumanModelPoints'] += experimentalScore; } else if (experimental.rescue.rescueType && experimental.rescue.rescueType === 'Cell culture model') { scoreTableValues['rescueCellCultureCount'] += 1; scoreTableValues['rescueCellCulturePoints'] += experimentalScore; } else if (experimental.rescue.rescueType && experimental.rescue.rescueType === 'Patient cells') { scoreTableValues['rescuePatientCellsCount'] += 1; scoreTableValues['rescuePatientCellsPoints'] += experimentalScore; } } } else if (score.scoreStatus === 'Contradicts') { // set flag if a contradicting experimental evidence is found contradictingEvidence.experimental = true; } } }); } }); }); // scan probands probandTotal.forEach(proband => { proband.scores.forEach(score => { if ((score.affiliation && curatorAffiliation && score.affiliation === curatorAffiliation.affiliation_id) || (!score.affiliation && !curatorAffiliation && score.submitted_by.uuid === this.state.user)) { if (score.scoreStatus === 'Score') { // parse proband score let probandScore = 0; if ('score' in score && score.score !== 'none') { probandScore += parseFloat(score.score); } else if ('calculatedScore' in score && score.calculatedScore !== 'none') { probandScore += parseFloat(score.calculatedScore); } // assign score to correct sub-type depending on score type if (score.caseInfoType && score.caseInfoType === 'OTHER_VARIANT_TYPE_WITH_GENE_IMPACT' && score.scoreStatus === 'Score') { scoreTableValues['probandOtherVariantCount'] += 1; scoreTableValues['probandOtherVariantPoints'] += probandScore; } else if (score.caseInfoType && score.caseInfoType === 'PREDICTED_OR_PROVEN_NULL_VARIANT' && score.scoreStatus === 'Score') { scoreTableValues['probandNullVariantCount'] += 1; scoreTableValues['probandNullVariantPoints'] += probandScore; } else if (score.caseInfoType && score.caseInfoType === 'VARIANT_IS_DE_NOVO' && score.scoreStatus === 'Score') { scoreTableValues['variantDenovoCount'] += 1; scoreTableValues['variantDenovoPoints'] += probandScore; } else if (score.caseInfoType && score.caseInfoType === 'TWO_VARIANTS_WITH_GENE_IMPACT_IN_TRANS' && score.scoreStatus === 'Score') { scoreTableValues['twoVariantsNotProvenCount'] += 1; scoreTableValues['twoVariantsNotProvenPoints'] += probandScore; } else if (score.caseInfoType && score.caseInfoType === 'TWO_VARIANTS_IN_TRANS_WITH_ONE_DE_NOVO' && score.scoreStatus === 'Score') { scoreTableValues['twoVariantsProvenCount'] += 1; scoreTableValues['twoVariantsProvenPoints'] += probandScore; } } else if (score.scoreStatus === 'Contradicts') { // set flag if a contradicting proband evidence is found contradictingEvidence.proband = true; } } }); }); // calculate segregation counted points scoreTableValues['segregationCountTotal'] = scoreTableValues['segregationCountCandidate'] + scoreTableValues['segregationCountExome']; // Total LOD scores is calculated from the sum of all LOD scores from both sequencing methods scoreTableValues['segregationTotalPoints'] = (scoreTableValues['segregationPointsCandidate'] + scoreTableValues['segregationPointsExome']); // Determine the min points (Candidate gene sequencing) and max points (Exome/genome or all genes sequenced in linkage region) given the total LOD scores let range = {min: 0, max: 0}; if (scoreTableValues['segregationTotalPoints'] >= 0 && scoreTableValues['segregationTotalPoints'] <= 1.99) { range = {min: 0, max: 0}; } else if (scoreTableValues['segregationTotalPoints'] >= 2 && scoreTableValues['segregationTotalPoints'] <= 2.99) { range = {min: 0.5, max: 1}; } else if (scoreTableValues['segregationTotalPoints'] >= 3 && scoreTableValues['segregationTotalPoints'] <= 4.99) { range = {min: 1, max: 2}; } else if (scoreTableValues['segregationTotalPoints'] >= 5) { range = {min: 1.5, max: 3}; } // Determine the 'awarded' exome points given the total exome LOD score let awardedExomePoints = 0; if (scoreTableValues['segregationPointsExome'] >= 0 && scoreTableValues['segregationPointsExome'] <= 1.99) { awardedExomePoints = 0; } else if (scoreTableValues['segregationPointsExome'] >= 2 && scoreTableValues['segregationPointsExome'] <= 2.99) { awardedExomePoints = 1; } else if (scoreTableValues['segregationPointsExome'] >= 3 && scoreTableValues['segregationPointsExome'] <= 4.99) { awardedExomePoints = 2; } else if (scoreTableValues['segregationTotalPoints'] >= 5) { awardedExomePoints = 3; } // Calculate the segregation points counted given total LOD scores, min points and max points let calculatedSegregationScore = scoreTableValues['segregationTotalPoints'] === parseFloat(0) ? parseFloat(0) : ((scoreTableValues['segregationPointsCandidate'] / scoreTableValues['segregationTotalPoints']) * range['min']) + ((scoreTableValues['segregationPointsExome'] / scoreTableValues['segregationTotalPoints']) * range['max']); // Determine which score to use - the calculated or the awarded Exome, given the total Exome LOD score range (e.g. 3 - 4.99) // Example 1 - total Exome LOD score = 3.1, awarded Exome points = 2, calculated score = 1.720930233, then final score = 2 // Example 2 - total Exome LOD score = 2, awarded Exome points = 1, calculated score = 1.891644909, then final score = 1.9 (rounded to nearest 0.1) if (calculatedSegregationScore !== parseFloat(0) && scoreTableValues['segregationPointsExome'] !== parseFloat(0)) { scoreTableValues['segregationPointsCounted'] = awardedExomePoints >= calculatedSegregationScore ? awardedExomePoints : this.classificationMathRound(calculatedSegregationScore, 1); } else { scoreTableValues['segregationPointsCounted'] = this.classificationMathRound(calculatedSegregationScore, 1); } // calculate other counted points let tempPoints = 0; scoreTableValues['probandOtherVariantPoints'] = this.classificationMathRound(scoreTableValues['probandOtherVariantPoints'], 2); scoreTableValues['probandOtherVariantPointsCounted'] = scoreTableValues['probandOtherVariantPoints'] < MAX_SCORE_CONSTANTS.OTHER_VARIANT_TYPE_WITH_GENE_IMPACT ? scoreTableValues['probandOtherVariantPoints'] : MAX_SCORE_CONSTANTS.OTHER_VARIANT_TYPE_WITH_GENE_IMPACT; scoreTableValues['probandNullVariantPoints'] = this.classificationMathRound(scoreTableValues['probandNullVariantPoints'], 2); scoreTableValues['probandNullVariantPointsCounted'] = scoreTableValues['probandNullVariantPoints'] < MAX_SCORE_CONSTANTS.PREDICTED_OR_PROVEN_NULL_VARIANT ? scoreTableValues['probandNullVariantPoints'] : MAX_SCORE_CONSTANTS.PREDICTED_OR_PROVEN_NULL_VARIANT; scoreTableValues['variantDenovoPoints'] = this.classificationMathRound(scoreTableValues['variantDenovoPoints'], 2); scoreTableValues['variantDenovoPointsCounted'] = scoreTableValues['variantDenovoPoints'] < MAX_SCORE_CONSTANTS.VARIANT_IS_DE_NOVO ? scoreTableValues['variantDenovoPoints'] : MAX_SCORE_CONSTANTS.VARIANT_IS_DE_NOVO; scoreTableValues['twoVariantsProvenPoints'] = this.classificationMathRound(scoreTableValues['twoVariantsProvenPoints'], 2); scoreTableValues['twoVariantsNotProvenPoints'] = this.classificationMathRound(scoreTableValues['twoVariantsNotProvenPoints'], 2); tempPoints = scoreTableValues['twoVariantsProvenPoints'] + scoreTableValues['twoVariantsNotProvenPoints']; scoreTableValues['autosomalRecessivePointsCounted'] = tempPoints < MAX_SCORE_CONSTANTS.AUTOSOMAL_RECESSIVE ? tempPoints : MAX_SCORE_CONSTANTS.AUTOSOMAL_RECESSIVE; scoreTableValues['caseControlPointsCounted'] = scoreTableValues['caseControlPoints'] < MAX_SCORE_CONSTANTS.CASE_CONTROL ? scoreTableValues['caseControlPoints'] : MAX_SCORE_CONSTANTS.CASE_CONTROL; tempPoints = scoreTableValues['biochemicalFunctionPoints'] + scoreTableValues['proteinInteractionsPoints'] + scoreTableValues['expressionPoints']; scoreTableValues['functionalPointsCounted'] = tempPoints < MAX_SCORE_CONSTANTS.FUNCTIONAL ? tempPoints : MAX_SCORE_CONSTANTS.FUNCTIONAL; tempPoints = scoreTableValues['patientCellsPoints'] + scoreTableValues['nonPatientCellsPoints']; scoreTableValues['functionalAlterationPointsCounted'] = tempPoints < MAX_SCORE_CONSTANTS.FUNCTIONAL_ALTERATION ? tempPoints : MAX_SCORE_CONSTANTS.FUNCTIONAL_ALTERATION; tempPoints = scoreTableValues['nonHumanModelPoints'] + scoreTableValues['cellCulturePoints'] + scoreTableValues['rescueHumanModelPoints'] + scoreTableValues['rescueNonHumanModelPoints'] + scoreTableValues['rescueCellCulturePoints'] + scoreTableValues['rescuePatientCellsPoints']; scoreTableValues['modelsRescuePointsCounted'] = tempPoints < MAX_SCORE_CONSTANTS.MODELS_RESCUE ? tempPoints : MAX_SCORE_CONSTANTS.MODELS_RESCUE; tempPoints = scoreTableValues['probandOtherVariantPointsCounted'] + scoreTableValues['probandNullVariantPointsCounted'] + scoreTableValues['variantDenovoPointsCounted'] + scoreTableValues['autosomalRecessivePointsCounted'] + scoreTableValues['segregationPointsCounted'] + scoreTableValues['caseControlPointsCounted']; scoreTableValues['geneticEvidenceTotalPoints'] = tempPoints < MAX_SCORE_CONSTANTS.GENETIC_EVIDENCE ? this.classificationMathRound(tempPoints, 2) : MAX_SCORE_CONSTANTS.GENETIC_EVIDENCE; tempPoints = scoreTableValues['functionalPointsCounted'] + scoreTableValues['functionalAlterationPointsCounted'] + scoreTableValues['modelsRescuePointsCounted']; scoreTableValues['experimentalEvidenceTotalPoints'] = tempPoints < MAX_SCORE_CONSTANTS.EXPERIMENTAL_EVIDENCE ? this.classificationMathRound(tempPoints, 2) : MAX_SCORE_CONSTANTS.EXPERIMENTAL_EVIDENCE; let totalScore = scoreTableValues['geneticEvidenceTotalPoints'] + scoreTableValues['experimentalEvidenceTotalPoints']; // set scoreTabValues state this.setState({totalScore: this.classificationMathRound(totalScore, 2), contradictingEvidence: contradictingEvidence, scoreTableValues: scoreTableValues}); // set classification this.calculateClassifications(totalScore, scoreTableValues['geneticEvidenceTotalPoints'], contradictingEvidence, this.state.replicatedOverTime); }, calculateClassifications: function(totalPoints, geneticEvidencePoints, contradictingEvidence, replicatedOverTime) { let autoClassification = "No Classification"; // If no scored genetic evidence and no contradicting evidence, calculated classification should be "No Known Disease Relationship" if (geneticEvidencePoints === 0 && !contradictingEvidence.caseControl && !contradictingEvidence.experimental && !contradictingEvidence.proband) { autoClassification = "No Known Disease Relationship"; } else if (totalPoints >= 0.1 && totalPoints <= 6) { autoClassification = "Limited"; } else if (totalPoints > 6 && totalPoints <= 11) { autoClassification = "Moderate"; } else if (totalPoints > 11 && totalPoints <= 18 && !replicatedOverTime) { autoClassification = "Strong"; } else if (totalPoints > 11 && totalPoints <= 18 && replicatedOverTime) { autoClassification = "Definitive"; } this.setState({autoClassification: autoClassification}, () => { // Reset modified classification state to 'No Modification' // if the new and current calculated classification is the same if (this.state.alteredClassification === this.state.autoClassification) { this.setState({ alteredClassification: 'No Modification', resetAlteredClassification: true }); } }); }, /** * Simple Math.round method * alternative #1 - Math.round(num * 10) / 10; //*** returns 1 decimal * alternative #2 - Math.round((num + 0.00001) * 100) / 100; //*** returns 2 decimals */ classificationMathRound(number, decimals) { return Number(Math.round(number + ('e' + decimals)) + ('e-' + decimals)); }, /** * Precision Math.round method * Example: this.precisionMathRound(0.30000000004, 2) // Result: 0.3 * Example: this.precisionMathRound(0.35000000004, 2) // Result: 0.35 */ precisionMathRound(number, precision) { let factor = Math.pow(10, precision); let tempNumber = number * factor; let roundedTempNumber = Math.round(tempNumber); return roundedTempNumber / factor; }, render: function() { this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href); let calculate = queryKeyValue('calculate', this.props.href); let edit = queryKeyValue('edit', this.props.href); let session = (this.props.session && Object.keys(this.props.session).length) ? this.props.session : null; const context = this.props.context; const currOmimId = this.state.currOmimId; let gdm = this.state.gdm ? this.state.gdm : null; let autoClassification = this.state.autoClassification; let scoreTableValues = this.state.scoreTableValues; let show_clsfctn = queryKeyValue('classification', this.props.href); let summaryMatrix = queryKeyValue('summarymatrix', this.props.href); let expMatrix = queryKeyValue('expmatrix', this.props.href); // set the 'Current Classification' appropriately only if previous provisional exists let provisional = this.state.provisional; let currentClassification = 'None'; if (provisional.last_modified) { if (provisional.alteredClassification && provisional.alteredClassification !== 'No Modification') { currentClassification = provisional.alteredClassification; } else { currentClassification = provisional.autoClassification ? provisional.autoClassification : this.state.autoClassification; } } let sortedSnapshotList = this.state.classificationSnapshots.length ? sortListByDate(this.state.classificationSnapshots, 'date_created') : []; const lastSavedDate = currentClassification !== 'None' ? getClassificationSavedDate(provisional) : null; const affiliation = this.props.affiliation; const classificationStatus = this.state.classificationStatus; const allowPublishButton = gdm && gdm.disease ? allowPublishGlobal(affiliation, 'classification', gdm.modeInheritance, gdm.disease.diseaseId) : false; const currentSOP = provisional ? isScoringForCurrentSOP(provisional.classificationPoints) : false; const demoVersion = this.props.demoVersion; return ( <div> { show_clsfctn === 'display' ? <div>{ClassificationDefinition()}</div> : ( gdm ? <div> <RecordHeader gdm={gdm} omimId={currOmimId} updateOmimId={this.updateOmimId} session={session} summaryPage={true} linkGdm={true} affiliation={affiliation} classificationSnapshots={sortedSnapshotList} context={context} /> <div className="container summary-provisional-classification-wrapper"> <Form submitHandler={this.submitForm} formClassName="form-horizontal form-std"> <PanelGroup accordion> <Panel title="Calculated Classification Matrix" open> <div className="form-group"> <div className="summary-matrix-wrapper"> <table className="summary-matrix"> <tbody> <tr className="header large bg-gray separator-below"> <td colSpan="6">Evidence Type</td> <td>Count</td> <td>Total Points</td> <td>Points Counted</td> </tr> <tr> <td rowSpan="11" className="header"><div className="rotate-text"><div>Genetic Evidence</div></div></td> <td rowSpan="9" className="header"><div className="rotate-text"><div>Case-Level</div></div></td> <td rowSpan="5" className="header"><div className="rotate-text"><div>Variant</div></div></td> <td rowSpan="3" className="header">Autosomal Dominant OR X-linked Disorder</td> <td colSpan="2">Proband with other variant type with some evidence of gene impact</td> <td>{scoreTableValues['probandOtherVariantCount']}</td> <td>{scoreTableValues['probandOtherVariantPoints']}</td> <td>{scoreTableValues['probandOtherVariantPointsCounted']}</td> </tr> <tr> <td colSpan="2">Proband with predicted or proven null variant</td> <td>{scoreTableValues['probandNullVariantCount']}</td> <td>{scoreTableValues['probandNullVariantPoints']}</td> <td>{scoreTableValues['probandNullVariantPointsCounted']}</td> </tr> <tr> <td colSpan="2">Variant is <i>de novo</i></td> <td>{scoreTableValues['variantDenovoCount']}</td> <td>{scoreTableValues['variantDenovoPoints']}</td> <td>{scoreTableValues['variantDenovoPointsCounted']}</td> </tr> <tr> <td rowSpan="2" className="header">Autosomal Recessive Disorder</td> <td colSpan="2">Two variants (not predicted/proven null) with some evidence of gene impact in <i>trans</i></td> <td>{scoreTableValues['twoVariantsNotProvenCount']}</td> <td>{scoreTableValues['twoVariantsNotProvenPoints']}</td> <td rowSpan="2">{scoreTableValues['autosomalRecessivePointsCounted']}</td> </tr> <tr> <td colSpan="2">Two variants in <i>trans</i> and at least one <i>de novo</i> or a predicted/proven null variant</td> <td>{scoreTableValues['twoVariantsProvenCount']}</td> <td>{scoreTableValues['twoVariantsProvenPoints']}</td> </tr> <tr> <td colSpan="2" rowSpan="4" className="header">Segregation</td> <td className="bg-gray"><span></span></td> <td className="header">Summed LOD</td> <td className="header">Family Count</td> <td rowSpan="4">{scoreTableValues['segregationPointsCounted']}</td> <td rowSpan="4">{scoreTableValues['segregationPointsCounted']}</td> </tr> <tr> <td>Candidate gene sequencing</td> <td><span>{this.classificationMathRound(scoreTableValues['segregationPointsCandidate'], 2)}</span></td> <td>{scoreTableValues['segregationCountCandidate']}</td> </tr> <tr> <td>Exome/genome or all genes sequenced in linkage region</td> <td><span>{this.classificationMathRound(scoreTableValues['segregationPointsExome'], 2)}</span></td> <td>{scoreTableValues['segregationCountExome']}</td> </tr> <tr> <td className="header">Total Summed LOD Score</td> <td className="header">{this.classificationMathRound(scoreTableValues['segregationTotalPoints'], 2)}</td> <td className="bg-gray"><span></span></td> </tr> <tr> <td colSpan="5" className="header">Case-Control</td> <td>{scoreTableValues['caseControlCount']}</td> <td>{scoreTableValues['caseControlPoints']}</td> <td>{scoreTableValues['caseControlPointsCounted']}</td> </tr> <tr className="header separator-below"> <td colSpan="7">Genetic Evidence Total</td> <td>{scoreTableValues['geneticEvidenceTotalPoints']}</td> </tr> <tr> <td rowSpan="12" className="header"><div className="rotate-text"><div>Experimental Evidence</div></div></td> <td colSpan="3" rowSpan="3" className="header">Functional</td> <td colSpan="2">Biochemical Functions</td> <td>{scoreTableValues['biochemicalFunctionCount']}</td> <td>{scoreTableValues['biochemicalFunctionPoints']}</td> <td rowSpan="3">{scoreTableValues['functionalPointsCounted']}</td> </tr> <tr> <td colSpan="2">Protein Interactions</td> <td>{scoreTableValues['proteinInteractionsCount']}</td> <td>{scoreTableValues['proteinInteractionsPoints']}</td> </tr> <tr> <td colSpan="2">Expression</td> <td>{scoreTableValues['expressionCount']}</td> <td>{scoreTableValues['expressionPoints']}</td> </tr> <tr> <td colSpan="3" rowSpan="2" className="header">Functional Alteration</td> <td colSpan="2">Patient cells</td> <td>{scoreTableValues['patientCellsCount']}</td> <td>{scoreTableValues['patientCellsPoints']}</td> <td rowSpan="2">{scoreTableValues['functionalAlterationPointsCounted']}</td> </tr> <tr> <td colSpan="2">Non-patient cells</td> <td>{scoreTableValues['nonPatientCellsCount']}</td> <td>{scoreTableValues['nonPatientCellsPoints']}</td> </tr> <tr> <td colSpan="3" rowSpan="2" className="header">Models</td> <td colSpan="2">Non-human model organism</td> <td>{scoreTableValues['nonHumanModelCount']}</td> <td>{scoreTableValues['nonHumanModelPoints']}</td> <td rowSpan="6">{scoreTableValues['modelsRescuePointsCounted']}</td> </tr> <tr> <td colSpan="2">Cell culture model</td> <td>{scoreTableValues['cellCultureCount']}</td> <td>{scoreTableValues['cellCulturePoints']}</td> </tr> <tr> <td colSpan="3" rowSpan="4" className="header">Rescue</td> <td colSpan="2">Rescue in human</td> <td>{scoreTableValues['rescueHumanModelCount']}</td> <td>{scoreTableValues['rescueHumanModelPoints']}</td> </tr> <tr> <td colSpan="2">Rescue in non-human model organism</td> <td>{scoreTableValues['rescueNonHumanModelCount']}</td> <td>{scoreTableValues['rescueNonHumanModelPoints']}</td> </tr> <tr> <td colSpan="2">Rescue in cell culture model</td> <td>{scoreTableValues['rescueCellCultureCount']}</td> <td>{scoreTableValues['rescueCellCulturePoints']}</td> </tr> <tr> <td colSpan="2">Rescue in patient cells</td> <td>{scoreTableValues['rescuePatientCellsCount']}</td> <td>{scoreTableValues['rescuePatientCellsPoints']}</td> </tr> <tr className="header separator-below"> <td colSpan="7">Experimental Evidence Total</td> <td>{scoreTableValues['experimentalEvidenceTotalPoints']}</td> </tr> <tr className="total-row header"> <td colSpan="8">Total Points</td> <td>{this.state.totalScore}</td> </tr> </tbody> </table> </div> <div className="summary-provisional-classification-description"> <p className="alert alert-warning"> <i className="icon icon-exclamation-circle"></i> The <strong>Total Points</strong> shown above are based on the set of saved evidence and accompanying scores existing when the "View Classification Matrix" button was clicked. To save a Classification for this Gene Disease Record based on this evidence, please see the section below. </p> </div> <div className="provisional-classification-wrapper"> <table className="summary-matrix"> <tbody> <tr className="header large bg-gray"> <td colSpan="5">Gene/Disease Pair</td> </tr> <tr> <td>Assertion Criteria</td> <td>Genetic Evidence (0-12 points)</td> <td>Experimental Evidence (0-6 points)</td> <td>Total Points (0-18 points)</td> <td>Replication Over Time (Yes/No) <ContextualHelp content="> 2 pubs w/ convincing evidence over time (>3 yrs)" /></td> </tr> <tr className="header large bg-gray separator-below"> <td>Assigned Points</td> <td>{scoreTableValues['geneticEvidenceTotalPoints']}</td> <td>{scoreTableValues['experimentalEvidenceTotalPoints']}</td> <td>{this.state.totalScore}</td> <td> <input type="checkbox" className="checkbox" onChange={this.handleReplicatedOverTime} checked={this.state.replicatedOverTime} /> </td> </tr> <tr className="header large"> <td colSpan="2" rowSpan="5">Calculated Classification</td> <td className={autoClassification === 'No Known Disease Relationship' ? ' bg-emphasis' : null}>No Known Disease Relationship</td> <td colSpan="2" className={autoClassification === 'No Known Disease Relationship' ? ' bg-emphasis' : null}>No Scored Genetic Evidence & No Contradictory Evidence</td> </tr> <tr className={"header large" + (autoClassification === 'Limited' ? ' bg-emphasis' : null)}> <td>LIMITED</td> <td colSpan="2">0.1-6</td> </tr> <tr className={"header large" + (autoClassification === 'Moderate' ? ' bg-emphasis' : null)}> <td>MODERATE</td> <td colSpan="2">7-11</td> </tr> <tr className={"header large" + (autoClassification === 'Strong' ? ' bg-emphasis' : null)}> <td>STRONG</td> <td colSpan="2">12-18</td> </tr> <tr className={"header large" + (autoClassification === 'Definitive' ? ' bg-emphasis' : null)}> <td>DEFINITIVE</td> <td colSpan="2">12-18 & Replicated Over Time</td> </tr> <tr> <td colSpan="2" className="header large">Contradictory Evidence?</td> <td colSpan="3"> Proband: <strong>{this.state.contradictingEvidence.proband ? <span className='emphasis'>Yes</span> : 'No'}</strong>&nbsp;&nbsp;&nbsp; {/*Case-control: <strong>{this.state.contradictingEvidence.caseControl ? <span className='emphasis'>Yes</span> : 'No'}</strong>&nbsp;&nbsp;&nbsp;*/} Experimental: <strong>{this.state.contradictingEvidence.experimental ? <span className='emphasis'>Yes</span> : 'No'}</strong>&nbsp;&nbsp;&nbsp; </td> </tr> <tr> <td colSpan="5"> <a name="classification-view" id="classification-view"></a> <div className="col-md-12 classification-form-content-wrapper"> <div className="col-xs-12 col-sm-6"> <div className="altered-classification"> <Input type="select" ref="alteredClassification" label={<strong>Modify Calculated <a href="/provisional-curation/?classification=display" target="_block">Clinical Validity Classification</a>:</strong>} error={this.getFormError('alteredClassification')} clearError={this.clrFormErrors.bind(null, 'alteredClassification')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue={this.state.alteredClassification} handleChange={this.handleChange}> <option value="No Modification">No Modification</option> {autoClassification === 'Definitive' ? null : <option value="Definitive">Definitive</option>} {autoClassification === 'Strong' ? null : <option value="Strong">Strong</option>} {autoClassification === 'Moderate' ? null : <option value="Moderate">Moderate</option>} {autoClassification === 'Limited' ? null : <option value="Limited">Limited</option>} <option value="Disputed">Disputed</option> <option value="Refuted">Refuted</option> <option value="No Known Disease Relationship">No Known Disease Relationship (calculated score is based on Experimental evidence only)</option> </Input> </div> <div className="altered-classification-reasons"> <Input type="textarea" ref="reasons" rows="5" label="Explain Reason(s) for Change:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" error={this.getFormError('reasons')} value={this.state.reasons} clearError={this.clrFormErrors.bind(null, 'reasons')} handleChange={this.handleChange} required={this.state.alteredClassification !== 'No Modification' ? true : false} placeholder="Note: This text will appear on ClinGen's website if you publish this Classification." customErrorMsg="Required when changing classification" /> {this.state.resetAlteredClassification ? <div className="altered-classification-reset-warning"> <div className="alert alert-danger"> <i className="icon icon-exclamation-triangle"></i> This value has been reset to "No Modification" as the Calculated Classification based on the new Total Points is now equivalent to your last saved Classification value. Click "Save" to save the Calculated Classification value, or modify to a new value and click "Save." </div> </div> : null} </div> </div> <div className="col-xs-12 col-sm-6"> <div className="classification-evidence-summary"> <Input type="textarea" ref="classification-evidence-summary" value={this.state.evidenceSummary} handleChange={this.handleChange} label={<span className="label-main">Evidence Summary (optional):<span className="label-note">Rationale for the clinical validity classification</span><br /> <span className="label-note"><a href="https://clinicalgenome.org/site/assets/files/3439/gene_curation_evidence_summary_12_11_18.pdf" target="_block">View Example Evidence Summary Text</a></span></span>} placeholder="Note: This text will appear on ClinGen's website if you publish this Classification." rows="8" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" /> </div> </div> </div> </td> </tr> <tr className="total-row header"> <td colSpan="2">Last Saved Summary Classification</td> <td colSpan="3"> {currentClassification == 'None' ? <span>{currentClassification}</span> : <div>{currentClassification}<span>&nbsp;{renderAnimalOnlyTag(provisional)}</span> <br /> <span className="large">({moment(lastSavedDate).format("YYYY MMM DD, h:mm a")})</span> </div> } </td> </tr> </tbody> </table> </div> <div> {Object.keys(provisional).length ? <p className="alert alert-info"> <i className="icon icon-info-circle"></i> Click Save to save the Calculated Classification (highlighted in blue) without modification, or modify the Classification value in the pull-down and hit Save. Once it is saved, you will have the opportunity to edit the saved Classification, view the Evidence Summary for the saved Classification, and save it as Provisional. </p> : <p className="alert alert-info"> <i className="icon icon-info-circle"></i> The Classification Matrix at the top of the page was calculated based on the current evidence and accompanying scores saved in the database when you clicked the "View Classification Matrix" button to navigate to this page. To save a new Classification, optionally modifying the Classification and/or adding an Evidence Summary, please fill in any desired fields above and click "Save". Otherwise, click "Cancel".<br /><br /> After saving, you will be able to view the Evidence Summary for the saved Classification, and be presented with the option to save it as a <strong>Provisional</strong> Classification (and then <strong>Approved</strong>). </p> } </div> </div> </Panel> </PanelGroup> <div className='modal-footer'> <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancelForm} title="Cancel" /> <Input type="submit" inputClassName="btn-primary btn-inline-spacer pull-right" id="submit" title="Save" /> </div> </Form> {sortedSnapshotList.length && (!allowPublishButton || !currentSOP)? <div> <p className="alert alert-info"> <i className="icon icon-info-circle"></i> The option to publish an approved classification is unavailable when any of the following apply: 1) your affiliation does not have permission to publish in the GCI, 2) the mode of inheritance is not supported by the Clinical Validity Classification framework, 3) the associated disease does not have a MONDO ID, 4) it is based on a previous version of the SOP. </p> </div> : null} {sortedSnapshotList.length ? <div className="snapshot-list"> <PanelGroup> <Panel title="Saved Provisional and Approved Classification(s)" panelClassName="panel-data" open> <CurationSnapshots snapshots={sortedSnapshotList} classificationStatus={classificationStatus} allowPublishButton={allowPublishButton} demoVersion={demoVersion} context={context} /> </Panel> </PanelGroup> </div> : null} </div> </div> : null ) } </div> ); } }); curator_page.register(ProvisionalCuration, 'curator_page', 'provisional-curation'); // Display a history item for adding a family class ProvisionalAddModHistory extends Component { render() { var history = this.props.history; var meta = history.meta.provisionalClassification; var gdm = meta.gdm; var provisional = history.primary; return ( <div> <span><a href={'/provisional-curation/?gdm=' + gdm.uuid + '&edit=yes'} title="View/edit provisional classification">Provisional classification</a> {meta.alteredClassification.toUpperCase()} added to </span> <strong>{gdm.gene.symbol}-{gdm.disease.term}-</strong> <i>{gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}</i> <span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span> </div> ); } } history_views.register(ProvisionalAddModHistory, 'provisionalClassification', 'add'); // Display a history item for modifying a family class ProvisionalModifyHistory extends Component { render() { var history = this.props.history; var meta = history.meta.provisionalClassification; var gdm = meta.gdm; var provisional = history.primary; return ( <div> <span><a href={'/provisional-curation/?gdm=' + gdm.uuid + '&edit=yes'} title="View/edit provisional classification">Provisional classification</a> modified to {meta.alteredClassification.toUpperCase()} for </span> <strong>{gdm.gene.symbol}-{gdm.disease.term}-</strong> <i>{gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}</i> <span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span> </div> ); } } history_views.register(ProvisionalModifyHistory, 'provisionalClassification', 'modify'); // Display a history item for deleting a family class ProvisionalDeleteHistory extends Component { render() { return <div>PROVISIONALDELETE</div>; } } history_views.register(ProvisionalDeleteHistory, 'provisionalClassification', 'delete');
src/components/Link/PhoneLink.js
cityofsurrey/polltal-app
import React from 'react' import PropTypes from 'prop-types' import Link from './Link' /** * Link for phone number that will trigger a calling */ const PhoneLink = ({ to, children }) => { const phone = to.replace(/[- ]/g, '') return ( <Link to={`tel:+1${phone}`}>{children}</Link> ) } PhoneLink.propTypes = { to: PropTypes.string.isRequired, children: PropTypes.string.isRequired, } export default PhoneLink
components/Queries.js
react-community/native-directory
import React from 'react'; import PropTypes from 'prop-types'; import Router from 'next/router'; import { StyleSheet, css } from 'glamor/aphrodite'; import { isEmptyOrNull } from '../common/strings'; export default class Queries extends React.PureComponent { static propTypes = { dispatch: PropTypes.func, queryTopic: PropTypes.string, querySearch: PropTypes.string, sortBy: PropTypes.string, }; _handleClearTopic = () => { window.location.href = `/${this.props.sortBy}`; }; _handleClearSearch = () => { window.location.href = `/${this.props.sortBy}`; }; render() { if (isEmptyOrNull(this.props.querySearch) && isEmptyOrNull(this.props.queryTopic)) { return null; } return ( <div className={css(styles.container)}> <h2 className={css(styles.heading)}>Your queries</h2> <ul className={css(styles.list)}> {!isEmptyOrNull(this.props.querySearch) && ( <li className={css(styles.item)}> <div className={css(styles.itemLeft)}> Searching for{' '} <strong className={css(styles.itemEmphasis)}> “ {this.props.querySearch} ” </strong>{' '} —{' '} <span className={css(styles.itemRight)}> <span className={css(styles.itemLink)} onClick={this._handleClearSearch}> Clear search </span> </span> </div> </li> )} {!isEmptyOrNull(this.props.queryTopic) && ( <li className={css(styles.item)}> <div className={css(styles.itemLeft)}> Selected{' '} <strong className={css(styles.itemEmphasis)}> “{this.props.queryTopic} ”{' '} </strong>{' '} —{' '} <span className={css(styles.itemRight)}> <span className={css(styles.itemLink)} onClick={this._handleClearTopic}> Clear topic </span> </span> </div> </li> )} </ul> </div> ); } } let styles = StyleSheet.create({ container: { padding: '27px 0 8px 0', }, heading: { fontFamily: `'office-code-medium', monospace`, fontWeight: '400', }, list: { display: 'block', }, item: { fontFamily: `'office-code', monospace`, display: 'block', margin: '8px 0 0 0', lineHeight: '1.2rem', }, itemEmphasis: { fontFamily: `'office-code-medium', monospace`, color: `rgba(250, 70, 83, 1)`, }, itemLeft: { overflowWrap: 'break-word', wordBreak: 'break-word', minWidth: '25%', width: '100%', }, itemRight: { flexShrink: 0, }, itemLink: { display: 'inline-block', textDecoration: 'underline', transition: 'all 200ms ease', transitionProperty: 'opacity, transform', cursor: 'pointer', ':hover': { opacity: 0.5, }, }, });
src/widgets/InlineInput.js
rcdexta/react-trello
import React from 'react' import PropTypes from 'prop-types' import {InlineInput} from 'rt/styles/Base' import autosize from 'autosize' class InlineInputController extends React.Component { onFocus = (e) => e.target.select() // This is the way to select all text if mouse clicked onMouseDown = (e) => { if (document.activeElement != e.target) { e.preventDefault() this.refInput.focus() } } onBlur = () => { this.updateValue() } onKeyDown = (e) => { if(e.keyCode == 13) { this.refInput.blur() e.preventDefault() } if(e.keyCode == 27) { this.setValue(this.props.value) this.refInput.blur() e.preventDefault() } if(e.keyCode == 9) { if (this.getValue().length == 0) { this.props.onCancel() } this.refInput.blur() e.preventDefault() } } getValue = () => this.refInput.value setValue = (value) => this.refInput.value=value updateValue = () => { if (this.getValue() != this.props.value) { this.props.onSave(this.getValue()) } } setRef = (ref) => { this.refInput = ref if (this.props.resize != 'none') { autosize(this.refInput) } } UNSAFE_componentWillReceiveProps(nextProps) { this.setValue(nextProps.value) } render() { const {autoFocus, border, value, placeholder} = this.props return <InlineInput ref={this.setRef} border={border} onMouseDown={this.onMouseDown} onFocus={this.onFocus} onBlur={this.onBlur} onKeyDown={this.onKeyDown} placeholder={value.length == 0 ? undefined : placeholder} defaultValue={value} autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck="false" dataGramm="false" rows={1} autoFocus={autoFocus} /> } } InlineInputController.propTypes = { onSave: PropTypes.func, border: PropTypes.bool, placeholder: PropTypes.string, value: PropTypes.string, autoFocus: PropTypes.bool, resize: PropTypes.oneOf(['none', 'vertical', 'horizontal']), } InlineInputController.defaultProps = { onSave: () => {}, placeholder: '', value: '', border: false, autoFocus: false, resize: 'none' } export default InlineInputController
shared/fee/flat.js
RalphSleigh/bookings
import React from 'react' //This event has a flat per participant cost. import { Button, Row, Col, Form, FormGroup, Label, Input, InputGroup, InputGroupAddon, Card, CardBody, CardTitle, CardImg, CardImgOverlay, Table } from 'reactstrap'; import Currency from "react-currency-formatter"; import {Item} from "react-html-email"; import cloneDeep from "lodash/cloneDeep"; import Moment from "moment"; import paymentLines from "./payment-lines"; export const name = "flat"; export const selection = "Flat fee per participant"; export class Config extends React.Component { constructor(props) { super(props); this.update = this.update.bind(this); } update(e) { const fee = {amount: e.target.value} this.props.update(fee); } render() { const amount = this.props.fee.amount || ""; return (<FormGroup row> <Label sm={3}>Fee per participant:</Label> <Col sm={9}> <InputGroup> <div className="input-group-prepend"> <span className="input-group-text">£</span> </div> <Input type="number" className="form-control" placeholder="35" value={amount} onChange={this.update}/> </InputGroup> </Col> </FormGroup>); } } export class BookingForm extends React.Component { render() { const participants = this.props.participants ? this.props.participants.length : 0 const total = this.props.feeData.amount * participants return (<Row> <Col> <p>This event costs £{this.props.feeData.amount} per person.</p> <p>You have booked <b>{participants}</b> {`${participants > 1 ? 'people' : 'person'}`} for a total of <b>£{total}</b></p> </Col> </Row>); } } export class ThanksRow extends React.Component { render() { const participants = this.props.booking.participants ? this.props.booking.participants.length : 0 const total = this.props.event.feeData.amount * participants return (<Row> <Col> <p>This event costs £{this.props.event.feeData.amount} per person.</p> <p>You have booked <b>{participants}</b> {`${participants > 1 ? 'people' : 'person'}`} for a total of <b>£{total}</b></p> </Col> </Row>); } } export function emailHTML(event, booking) { const rows = getFeesOwed(event, booking.participants, booking).map((r, i) => <tr key={i}> <td>{r.line}: </td> <td><b><Currency quantity={r.total} currency="GBP" /></b></td> </tr>); const total = rows.length > 1 ? <tr> <td><b>Total</b></td> <td><b><Currency quantity={feesOwed.reduce((a, c) => { return a + c.total }, 0)} currency="GBP" /></b></td> </tr> : null; return (<Item> <p><b>Money:</b></p> <table> <tbody> {rows} {total} </tbody> </table> </Item>) } export function getFeesOwed(event, participants, booking, payments=true) { const people = participants.length const result = { line: `${people} ${people > 1 ? 'people' : 'person'} at £${event.feeData.amount}`, total: event.feeData.amount * people } return [result, ...(payments ? paymentLines(event, participants, booking) : [])]; }
client/src/components/CategoryRow.js
Nauktis/inab
import React from 'react'; import Cell from './Cell'; import Amount from './Amount'; import ui from 'redux-ui'; import BudgetItemForm from './BudgetItemForm'; import {connect} from 'react-redux'; import asyncActionCreatorsFor from '../actions/asyncActionCreatorsFor'; import moment from 'moment'; import FontAwesome from 'react-fontawesome'; @ui() class CategoryRow extends React.Component { static propTypes = { category: React.PropTypes.object.isRequired, activity: React.PropTypes.number, available: React.PropTypes.number, ui: React.PropTypes.object, updateUI: React.PropTypes.func, create: React.PropTypes.func.isRequired, update: React.PropTypes.func.isRequired, budgetItem: React.PropTypes.object } editBudgetItem() { if ( !(this.props.budgetItem && this.props.budgetItem.busy) ) { this.props.updateUI('editingCategoryId', this.props.category.id); } } render() { var budgetCell; // TODO this is way too much logic for a component. This should be moved somwhere else. if (this.props.ui.editingCategoryId == this.props.category.id) { const onSubmit = (data) => { const m = moment([this.props.ui.year, this.props.ui.month - 1]); if (this.props.budgetItem) { this.props.update({ id: this.props.budgetItem.id, month: m.format("YYYY-MM-DD"), category_id: this.props.category.id, amount: Number(data.amount) * 100 }); } else { this.props.create({ month: m.format("YYYY-MM-DD"), category_id: this.props.category.id, amount: Number(data.amount) * 100 }); } this.props.updateUI('editingCategoryId', undefined); }; budgetCell = <Cell><BudgetItemForm onSubmit={onSubmit.bind(this)} /></Cell>; } else { budgetCell = <Cell onClick={() => this.editBudgetItem()}>{this.props.budgetItem && this.props.budgetItem.busy && <FontAwesome name='refresh' spin fixedWidth />}<Amount amount={this.props.budgetItem && this.props.budgetItem.amount} /></Cell>; } return ( <tr> <Cell>{this.props.category.name}</Cell> {budgetCell} <td><Amount amount={this.props.activity} /></td> <td><Amount amount={this.props.available} color /></td> </tr> ); } } export default connect(null, asyncActionCreatorsFor('budget_items'))(CategoryRow);
docs/client/components/pages/Linkify/index.js
koaninc/draft-js-plugins
import React, { Component } from 'react'; // eslint-disable-next-line import/no-unresolved import simpleExampleCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleLinkifyEditor'; // eslint-disable-next-line import/no-unresolved import simpleExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./SimpleLinkifyEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import customExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomLinkifyEditor'; // eslint-disable-next-line import/no-unresolved import customExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomLinkifyEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import customComponentExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomComponentLinkifyEditor'; // eslint-disable-next-line import/no-unresolved import customComponentExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomComponentLinkifyEditor/editorStyles.css'; // eslint-disable-next-line import/no-unresolved import gettingStarted from '!!../../../loaders/prism-loader?language=javascript!./gettingStarted'; // eslint-disable-next-line import/no-unresolved import webpackConfig from '!!../../../loaders/prism-loader?language=javascript!./webpackConfig'; // eslint-disable-next-line import/no-unresolved import webpackImport from '!!../../../loaders/prism-loader?language=javascript!./webpackImport'; import Container from '../../shared/Container'; import AlternateContainer from '../../shared/AlternateContainer'; import Heading from '../../shared/Heading'; import styles from './styles.css'; import Code from '../../shared/Code'; import SimpleLinkifyEditor from './SimpleLinkifyEditor'; import CustomLinkifyEditor from './CustomLinkifyEditor'; import CustomComponentLinkifyEditor from './CustomComponentLinkifyEditor'; import SocialBar from '../../shared/SocialBar'; import NavBar from '../../shared/NavBar'; import Separator from '../../shared/Separator'; import ExternalLink from '../../shared/Link'; import InlineCode from '../../shared/InlineCode'; export default class App extends Component { render() { return ( <div> <NavBar /> <Separator /> <Container> <Heading level={2}>Linkify</Heading> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}> Desktop: Yes </li> <li className={styles.listEntry}> Mobile: Yes </li> <li className={styles.listEntry}> Screen-reader: Yes </li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install draft-js-plugins-editor@beta --save" /> <Code code="npm install draft-js-linkify-plugin@beta --save" /> <Code code={gettingStarted} name="gettingStarted.js" /> <Heading level={3}>Importing the default styles</Heading> <p> The plugin ships with a default styling available at this location in the installed package: &nbsp; <InlineCode code={'node_modules/draft-js-linkify-plugin/lib/plugin.css'} /> </p> <Heading level={4}>Webpack Usage</Heading> <ul className={styles.list}> <li className={styles.listEntry}> 1. Install Webpack loaders: &nbsp; <InlineCode code={'npm i style-loader css-loader --save-dev'} /> </li> <li className={styles.listEntry}> 2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list. <Code code={webpackConfig} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 3. Add the below import line to your component to tell Webpack to inject the style to your component. <Code code={webpackImport} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 4. Restart Webpack. </li> </ul> <Heading level={4}>Browserify Usage</Heading> <p> Please help, by submiting a Pull Request to the <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Linkify/index.js">documentation</ExternalLink>. </p> </AlternateContainer> <Container> <Heading level={2}>Configuration Parameters</Heading> <div className={styles.param}> <span className={styles.paramName}>theme</span> <span>Object of CSS classes with the following keys.</span> <div className={styles.subParams}> <div className={styles.subParam}><span className={styles.subParamName}>link:</span> CSS class to be applied to link text</div> </div> </div> <div className={styles.param}> <span className={styles.paramName}>target</span> <span>String value for the target attribute. (Default value is _self)</span> </div> <div className={styles.param}> <span className={styles.paramName}>component</span> <span>If provided this component will be rendered instead of the default Anchor tag. It receives the following props: target, href & className</span> </div> </Container> <Container> <Heading level={2}>Simple Example</Heading> <SimpleLinkifyEditor /> <Code code={simpleExampleCode} name="SimpleLinkifyEditor.js" /> <Code code={simpleExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Themed Linkify Example</Heading> <CustomLinkifyEditor /> <Code code={customExampleCode} name="CustomLinkifyEditor.js" /> <Code code={customExampleEditorStylesCode} name="editorStyles.css" /> </Container> <Container> <Heading level={2}>Themed Linkify Example</Heading> <CustomComponentLinkifyEditor /> <Code code={customComponentExampleCode} name="CustomComponentLinkifyEditor.js" /> <Code code={customComponentExampleEditorStylesCode} name="editorStyles.css" /> </Container> <SocialBar /> </div> ); } }
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js
honpya/taketodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import IconButton from '../../../components/icon_button'; import { changeComposeSensitivity } from '../../../actions/compose'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ marked: { id: 'compose_form.sensitive.marked', defaultMessage: 'Media is marked as sensitive' }, unmarked: { id: 'compose_form.sensitive.unmarked', defaultMessage: 'Media is not marked as sensitive' }, }); const mapStateToProps = state => ({ visible: state.getIn(['compose', 'media_attachments']).size > 0, active: state.getIn(['compose', 'sensitive']), disabled: state.getIn(['compose', 'spoiler']), }); const mapDispatchToProps = dispatch => ({ onClick () { dispatch(changeComposeSensitivity()); }, }); class SensitiveButton extends React.PureComponent { static propTypes = { visible: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { visible, active, disabled, onClick, intl } = this.props; return ( <Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}> {({ scale }) => { const icon = active ? 'eye-slash' : 'eye'; const className = classNames('compose-form__sensitive-button', { 'compose-form__sensitive-button--visible': visible, }); return ( <div className={className} style={{ transform: `scale(${scale})` }}> <IconButton className='compose-form__sensitive-button__icon' title={intl.formatMessage(active ? messages.marked : messages.unmarked)} icon={icon} onClick={onClick} size={18} active={active} disabled={disabled} style={{ lineHeight: null, height: null }} inverted /> </div> ); }} </Motion> ); } } export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
client/pages/HomePage.js
marcocom/portfolio-react-webpack2
import React from 'react'; import { browserHistory } from 'react-router'; import { RaisedButton } from 'material-ui'; export default function HomePage() { const handleToCounter = () => browserHistory.push('counter'); const handleToTodo = () => browserHistory.push('todo'); const buttonStyles = { margin: '10px' }; return ( <div className="home-page"> <div className="container"> <div className="section link-section app-flex"> <h1 className="title is-1">React App</h1> <RaisedButton label="Counter App" style={buttonStyles} onClick={handleToCounter} /> <RaisedButton label="Todo App" style={buttonStyles} onClick={handleToTodo} /> </div> </div> </div> ); }
src/js/components/home/Banner.js
mmmigalll/react-starter
import React, { Component } from 'react'; import Button from './Button'; export default () => ( <div className="banner"> <h1> Intelligence Reports </h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <Button /> </div> );
src/playground/components/ListExample.react.js
Indoqa/indoqa-rebass-components
import React from 'react' import Div from '../../main/components/Div.react' import List from '../../main/components/List.react' import ListItem from '../../main/components/ListItem.react' import {Heading, Space, Pre} from 'rebass' const ListExample = () => ( <Div> <Heading level={2}> Lists </Heading> <Pre> &lt;List&gt; ... </Pre> <List> <ListItem> item 1 </ListItem> <ListItem> item 2 </ListItem> <ListItem> item 3 </ListItem> <ListItem> item 4 </ListItem> </List> <Space y={1} /> <Pre> &lt;List itemType="circle"&gt; ... </Pre> <List itemType="circle"> <ListItem> item 1 </ListItem> <ListItem> item 2 </ListItem> <ListItem> item 3 </ListItem> <ListItem> item 4 </ListItem> </List> <Space y={1} /> <Pre> &lt;List ordered&gt; ... </Pre> <List ordered> <ListItem> item 1 </ListItem> <ListItem> item 2 </ListItem> <ListItem> item 3 </ListItem> <ListItem> item 4 </ListItem> </List> <Pre> &lt;List ordered itemType="lower-alpha"&gt; ... </Pre> <List ordered itemType="lower-alpha"> <ListItem> item 1 </ListItem> <ListItem> item 2 </ListItem> <ListItem> item 3 </ListItem> <ListItem> item 4 </ListItem> </List> </Div> ) export default ListExample
componentes/TimeLine.js
yomi-network/app
import React, { Component } from 'react'; import { Image, Platform, StyleSheet, Text, View, ScrollView, } from 'react-native'; import {StackNavigator} from 'react-navigation'; import Terms from './Terminos'; import Header from './Header'; import * as RecipesApi from './RecipesFromApi'; import SearchBar from './SearchBar'; import Start from './Start'; import User from './User'; import * as Menus from './Menus'; import ImagePicker from './ImagePicker'; import Banner from './Banner'; import MenuBar from './MenuBar' const ModalStack = { ShowRecipe: { name: "Muestra una receta", description: "Muestra el detalle de la receta", path: 'ShowRecipe/:name', screen: RecipesApi.default.SingleRecipe, }, }; export default class TimeLine extends Component { constructor(props) { super(props) } render() { console.log(RecipesApi.default.Recipes); return( <View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-end'}}> <View> <Banner /> </View> <ScrollView> <View style={{marginTop: 60}}> <RecipesApi.default.Recipes /> </View> <View style={{marginTop: 60}}> <Menus.default.Menus /> </View> </ScrollView> <View> <MenuBar navigation={this.props.navigation}/> </View> </View> ) } }
src/parser/priest/holy/modules/core/HolyWordWastedAmounts.js
FaideWW/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatNumber } from 'common/format'; import SPELLS from 'common/SPELLS/index'; import Analyzer from 'parser/core/Analyzer'; // dependencies import HolyWordSanctify from 'parser/priest/holy/modules/spells/holyword/HolyWordSanctify'; import HolyWordChastise from 'parser/priest/holy/modules/spells/holyword/HolyWordChastise'; import HolyWordSerenity from 'parser/priest/holy/modules/spells/holyword/HolyWordSerenity'; class HolyWordWastedAmounts extends Analyzer { static dependencies = { sanctify: HolyWordSanctify, serenity: HolyWordSerenity, chastise: HolyWordChastise, }; statistic() { const percWastedVersusTotal = (this.serenity.holyWordWastedCooldown + this.sanctify.holyWordWastedCooldown) / (this.serenity.totalCooldownReduction + this.sanctify.totalCooldownReduction); return ( <StatisticBox icon={<SpellIcon id={SPELLS.HOLY_WORDS.id} />} value={`${formatPercentage(percWastedVersusTotal)}%`} label="Wasted Holy Words reduction" tooltip={` ${formatNumber(this.serenity.holyWordWastedCooldown / 1000)}s wasted Serenity reduction (of ${formatNumber(this.serenity.totalCooldownReduction / 1000)}s total)<br/> ${formatNumber(this.sanctify.holyWordWastedCooldown / 1000)}s wasted Sanctify reduction (of ${formatNumber(this.sanctify.totalCooldownReduction / 1000)}s total)<br/> `} position={STATISTIC_ORDER.CORE(4)} /> ); } } export default HolyWordWastedAmounts;
website/src/pages/line/canvas.js
plouc/nivo
import React from 'react' import omit from 'lodash/omit' import { ResponsiveLineCanvas, LineCanvasDefaultProps } from '@nivo/line' import { ComponentTemplate } from '../../components/components/ComponentTemplate' import meta from '../../data/components/line/meta.yml' import mapper from '../../data/components/line/mapper' import { groups } from '../../data/components/line/props' import defaultSettings from '../../data/components/line/defaults' import { generateHeavyDataSet } from '../../data/components/line/generator' import { graphql, useStaticQuery } from 'gatsby' const xValues = [0, 20, 40, 60, 80, 100, 120] const yValues = [0, 500, 1000, 1500, 2000, 2500] const initialProperties = { ...omit(defaultSettings, ['width', 'height']), useMesh: true, debugMesh: false, curve: 'monotoneX', pixelRatio: typeof window !== 'undefined' && window.devicePixelRatio ? window.devicePixelRatio : 1, margin: { top: 50, right: 160, bottom: 50, left: 60, }, enableArea: false, colors: { scheme: 'spectral' }, lineWidth: 1, xScale: { type: 'linear', }, yScale: { type: 'linear', stacked: true, min: 0, max: 2500, }, pointSize: 4, pointBorderWidth: 1, enableGridX: false, gridXValues: xValues, gridYValues: yValues, axisTop: { enable: false, tickValues: xValues, tickSize: 5, tickPadding: 5, tickRotation: 0, format: '.2f', legend: '', legendOffset: 36, }, axisRight: { enable: true, tickValues: yValues, tickSize: 5, tickPadding: 5, tickRotation: 0, format: '.2s', legend: '', legendOffset: 0, }, axisBottom: { enable: true, tickValues: xValues, tickSize: 5, tickPadding: 5, tickRotation: 0, format: '.2f', legend: 'price', legendOffset: 36, legendPosition: 'middle', }, axisLeft: { enable: true, tickValues: yValues, tickSize: 5, tickPadding: 5, tickRotation: 0, format: '.2s', legend: 'volume', legendOffset: -40, legendPosition: 'middle', }, legends: [ { anchor: 'bottom-right', direction: 'column', justify: false, translateX: 140, translateY: 0, itemsSpacing: 2, itemDirection: 'left-to-right', itemWidth: 80, itemHeight: 12, itemOpacity: 0.75, symbolSize: 12, symbolShape: 'circle', symbolBorderColor: 'rgba(0, 0, 0, .5)', onClick: data => { alert(JSON.stringify(data, null, ' ')) }, effects: [ { on: 'hover', style: { itemBackground: 'rgba(0, 0, 0, .03)', itemOpacity: 1, }, }, ], }, ], } const LineCanvas = () => { const { image: { childImageSharp: { gatsbyImageData: image }, }, } = useStaticQuery(graphql` query { image: file(absolutePath: { glob: "**/src/assets/captures/line-canvas.png" }) { childImageSharp { gatsbyImageData(layout: FIXED, width: 700, quality: 100) } } } `) return ( <ComponentTemplate name="Line" meta={meta.LineCanvas} icon="line" flavors={meta.flavors} currentFlavor="canvas" properties={groups} initialProperties={initialProperties} defaultProperties={LineCanvasDefaultProps} propertiesMapper={mapper} generateData={generateHeavyDataSet} getDataSize={data => data.length * data[0].data.length} image={image} > {(properties, data, theme, logAction) => { return ( <ResponsiveLineCanvas data={data} {...properties} theme={theme} onClick={point => { logAction({ type: 'click', label: `[point] serie: ${point.serieId}, x: ${point.data.x}, y: ${point.data.y}`, color: point.color, data: point, }) }} /> ) }} </ComponentTemplate> ) } export default LineCanvas
internals/templates/app.js
svangordon/latrones-cli
/** * 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 { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; 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-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, 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'), ])) .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 }
src/icons/AddAlertIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class AddAlertIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M20.02 41.02c0 2.2 1.78 3.98 3.98 3.98s3.98-1.78 3.98-3.98h-7.96zm17.74-8.38V21c0-6.5-4.5-11.94-10.58-13.38V6.18C27.18 4.42 25.76 3 24 3s-3.18 1.42-3.18 3.18v1.44C14.74 9.06 10.24 14.5 10.24 21v11.64L6 36.88V39h36v-2.12l-4.24-4.24zM32 25.01h-6v6h-4v-6h-6V21h6v-6h4v6h6v4.01z"/></svg>;} };
src/js/components/HomePage/HomePage.js
mnm1001/draggable-homepage
import React from 'react' import map from 'lodash/map' import isEmpty from 'lodash/isEmpty' import Category from 'components/HomePage/Category' import AddCategoryButton from 'components/HomePage/AddCategoryButton' import './HomePage.scss' import { DragDropContext } from 'react-dnd' import HTML5Backend from 'react-dnd-html5-backend' import * as DataService from 'services/data' import * as CategoryUtils from 'utils/category' import * as ItemUtils from 'utils/item' import Tabs from 'antd/lib/Tabs' import 'antd/dist/antd.css' @DragDropContext(HTML5Backend) export default class HomePage extends React.Component { constructor() { super() this.state = { jsonData: [], isEdit: false, searchWord: '', savePending: false, searchTimeOut: undefined, activeTagId: '' } this.handleClickSave = this.handleClickSave.bind(this) this.handleIsEdit = this.handleIsEdit.bind(this) this.handleChangeSearchWord = this.handleChangeSearchWord.bind(this) this.handleMoveCategory = this.handleMoveCategory.bind(this) this.handleAddCategory = this.handleAddCategory.bind(this) this.handleEditCategory = this.handleEditCategory.bind(this) this.handleDeleteCategory = this.handleDeleteCategory.bind(this) this.handleMoveItem = this.handleMoveItem.bind(this) this.handleMoveItemToEmptyCategory = this.handleMoveItemToEmptyCategory.bind(this) this.handleAddItem = this.handleAddItem.bind(this) this.handleEditItem = this.handleEditItem.bind(this) this.handleDeleteItem = this.handleDeleteItem.bind(this) this.handleChangeTags = this.handleChangeTags.bind(this) } componentWillMount() { DataService.loadData().then((jsonData) => { this.setState({jsonData, activeTagId: jsonData[0].id}) }) } componentWillUpdate (nextProps, nextState) { if (nextState.isEdit) { window.onbeforeunload = () => {return 'leave without save?'} } else { window.onbeforeunload = null } } handleClickSave() { if (!this.state.savePending) { this.setState({savePending: true}) DataService.saveData(this.state.jsonData).then( () => {this.setState({ isEdit: false, savePending: false }) }, () => {alert('save fail!')} ) } } handleIsEdit() { if (this.state.isEdit) { this.setState({isEdit: false}) } else { this.setState({isEdit: true}) } } handleMoveCategory(dragId, hoverId) { const jsonData = CategoryUtils.moveCategory(this.state.jsonData, dragId, hoverId) this.setState({ jsonData }) } handleAddCategory(newCategory) { const jsonData = CategoryUtils.addCategory(this.state.jsonData, newCategory) this.setState({ jsonData }) } handleEditCategory(newCategory) { const jsonData = CategoryUtils.editCategory(this.state.jsonData, newCategory) this.setState({ jsonData }) } handleDeleteCategory(categoryId) { const jsonData = CategoryUtils.deleteCategory(this.state.jsonData, categoryId) this.setState({ jsonData }) } handleMoveItem(dragId, hoverId) { const jsonData = ItemUtils.moveItem(this.state.jsonData, dragId, hoverId) this.setState({ jsonData }) } handleMoveItemToEmptyCategory(dragId, hoverCategoryId) { const jsonData = ItemUtils.moveItemToEmptyCategory(this.state.jsonData, dragId, hoverCategoryId) this.setState({ jsonData }) } handleAddItem(categoryId, newItem) { const jsonData = ItemUtils.addItem(this.state.jsonData, categoryId, newItem) this.setState({ jsonData }) } handleEditItem(categoryId, newItem) { const jsonData = ItemUtils.editItem(this.state.jsonData, categoryId, newItem) this.setState({ jsonData }) } handleDeleteItem(ItemId) { const jsonData = ItemUtils.deleteItem(this.state.jsonData, ItemId) this.setState({ jsonData }) } handleChangeSearchWord() { if (!isEmpty(this.state.searchTimeOut)) { clearTimeout(this.state.searchTimeOut) } this.setState({ searchTimeOut: setTimeout(() => { this.setState({ searchWord: this.refs.searchWord.value }) }, 300) }) } handleChangeTags(id) { console.log(id); this.setState({ activeTagId: id }) } render() { const {jsonData} = this.state return ( <div className='homePage'> <div className='Menu'> {this.renderMenu()} <input type='text' placeholder='defaultValue is sesword' onChange={this.handleChangeSearchWord} ref='searchWord'></input> </div> {this.renderTabs(jsonData)} {this.renderAddButton()} </div> ) } renderTabs(jsonData) { const TabPane = Tabs.TabPane const panes = map(jsonData, tab => <TabPane tab={tab.name} key={tab.id}>{this.renderCategories(tab.categories)}</TabPane> ) //console.log(panes); return ( <Tabs onChange={this.handleChangeTags} activeKey={this.state.activeTagId} type='editable-card' //onEdit={this.onEdit} > {panes} </Tabs> ) } renderCategories(categories) { return ( <div className='categories'> {map(categories, (category) => { return (<Category onMoveItem={this.handleMoveItem} onMoveItemToEmptyCategory={this.handleMoveItemToEmptyCategory} onAddItem={this.handleAddItem} onEditItem={this.handleEditItem} onDeleteItem={this.handleDeleteItem} category={category} isEdit={this.state.isEdit} key={category.id} searchWord={this.state.searchWord} onMoveCategory={this.handleMoveCategory} onEditCategory={this.handleEditCategory} onDeleteCategory={this.handleDeleteCategory} />) } )} </div> ) } renderMenu() { if (this.state.isEdit) { return ( <div> <span onClick={this.handleIsEdit}>取消</span> <span onClick={this.handleClickSave}>保存</span> </div> ) } return ( <div> <span onClick={this.handleIsEdit}>编辑</span> </div> ) } renderAddButton() { if (!this.state.isEdit) { return null } return ( <AddCategoryButton onAddCategory={this.handleAddCategory}/> ) } }
src/svg-icons/image/looks-5.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooks5 = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h2c1.1 0 2 .89 2 2v2c0 1.11-.9 2-2 2H9v-2h4v-2H9V7h6v2z"/> </SvgIcon> ); ImageLooks5 = pure(ImageLooks5); ImageLooks5.displayName = 'ImageLooks5'; ImageLooks5.muiName = 'SvgIcon'; export default ImageLooks5;
v3/test/views/layout/Footer.js
mauris/nusmods
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import Footer from 'views/layout/Footer'; test('is a footer element', (t) => { const actual = shallow(<Footer/>); t.is(actual.type(), 'footer'); }); // check for noopener noreferrer if target_blank was used // see: https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/ test('contains guards against target_blank', (t) => { const footer = shallow(<Footer/>); const links = footer.find('a'); let result = true; links.forEach((a) => { if (result && a.prop('target') === '_blank') { result = a.prop('rel') === 'noopener noreferrer'; } }); t.true(result); });
test/testHelper.js
nicksp/react-geo-weather
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/js/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/Cart/CartPage.js
KaPrimov/ArtPodarychePage
import React, { Component } from 'react'; import $ from 'jquery'; import ContactForm from './ContactForm'; import BoughtProductsList from './BoughtProductsList'; import '../../resources/styles/bought-products-styles.css'; import { withRouter } from 'react-router' import {sendEmail} from '../../models/mail-sender'; class CartPage extends Component { constructor(props) { super(props) this.state = { cart: [], price: 0, email: '', phone: '', username: '' } this.bindEventHandlers(); } bindEventHandlers() { this.onSubmitHandler= this.onSubmitHandler.bind(this); this.onChangeHandler=this.onChangeHandler.bind(this); this.showSuccess=this.showSuccess.bind(this); } componentDidMount() { $('.cart-wrapper').hide(); $('button.link-page').hide(); let totalPrice = 0; for (var key in this.props.location.state.products) { for (var innerKey in this.props.location.state.products[key]) { let product = this.props.location.state.products[key][innerKey]; totalPrice += (product.price * product.cartQuantity); } } this.setState({cart: this.props.location.state.products, price: totalPrice}); } componentWillUnmount() { $('button.link-page').show(); $('.cart-wrapper').show(); } onSubmitHandler(event) { event.preventDefault(); let email = this.state.email; let phone = this.state.phone; let name = this.state.username; sendEmail(email, phone, name, this.state.cart, this.showSuccess); } onChangeHandler(event) { switch (event.target.name) { case 'username': this.setState({ username: event.target.value }); break; case 'phone': this.setState({ phone: event.target.value }); break; case 'email': this.setState({email: event.target.value}) break; default: break; } } showSuccess(response) { this.props.router.push({ pathname: "/finish-order", }); window.location.reload(); } render() { return <div className='cart-page'> <h2 className='bought-products-header'>Закупени продукти:</h2> <BoughtProductsList products={this.state.cart} /> <h2 className='total-price'>Обща сума: {this.state.price}лв.</h2> <ContactForm clientName={this.state.username} email={this.state.email} phone={this.state.phone} onSubmitHandler={this.onSubmitHandler} onChangeHandler={this.onChangeHandler} /> </div> } } export default withRouter(CartPage)
src/components/button_adduser.js
robreczarek/recruitment-un
import React, { Component } from 'react'; import { Link } from 'react-router'; class ButtonAddUser extends Component { constructor(props) { super(props); this.maxUsers = 10 } userAdded() { const success = this.props.location.query.success; const error = this.props.location.query.error; if (success === 'true') { return ( <div className="notification"> <i className="fa fa-check success" aria-hidden="true"></i> You have successfully added a user. </div> ); } else if (success === 'false' && error) { return ( <div className="notification"> <i className="fa fa-exclamation-circle warning" aria-hidden="true"></i> {error} </div> ); } else { return null; } } render() { return ( <div className="barAddUser"> {this.renderButtonAddUser(this.props.users.users.length)} <div className="barNotifications"> {this.userAdded()} {this.renderTooManyUsers(this.props.users.users.length)} </div> </div> ); } renderButtonAddUser(numUsers) { if (numUsers < this.maxUsers) { return ( <div className="left buttonOutline"> <Link to="adduser"><i className="fa fa-plus-circle" aria-hidden="true"></i> Add User</Link> </div> ) } } renderTooManyUsers(numUsers) { if (numUsers >= this.maxUsers) { return ( <div className="notification"> <i className="fa fa-exclamation-circle warning" aria-hidden="true"></i> You have reached the maximum number of users. </div> ) } } } export default ButtonAddUser;
src/index.js
cephalization/filehub
// Import Styles import 'semantic-ui-css/semantic.min.css'; import './index.css'; // Import Components import React from 'react'; import ReactDOM from 'react-dom'; import MainComponent from './components/mainComponent'; // Misc import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<MainComponent />, document.getElementById('root')); registerServiceWorker();
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DestructuringAndAwait.js
g3r4n/create-esri-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; async function load() { return { users: [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ], }; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const { users } = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-destructuring-and-await"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
lib/ui/src/modules/ui/components/stories_panel/index.stories.js
rhalff/storybook
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import StoriesPanel from './index'; import { createHierarchies } from '../../libs/hierarchy'; import withLifecyle from '../../../../libs/withLifecycleDecorator'; import { setContext } from '../../../../compose'; const decorator = withLifecyle({ beforeEach() { setContext({ clientStore: { getAll() { return { shortcutOptions: {} }; }, subscribe() {}, }, }); }, afterEach() { setContext(null); }, }); const storiesHierarchies = createHierarchies([{ kind: 'kk', namespaces: ['kk'], stories: ['bb'] }]); const openShortcutsHelp = action('openShortcutsHelp'); const onStoryFilter = action('onStoryFilter'); storiesOf('ui/stories/StoriesPanel', module) .addDecorator(decorator) .add('default', () => ( <StoriesPanel filter="xxxxx" openShortcutsHelp={openShortcutsHelp} onStoryFilter={onStoryFilter} /> )) .add('with storiesHierarchies prop', () => ( <StoriesPanel storiesHierarchies={storiesHierarchies} selectedKind="kk" selectedStory="bb" selectedHierarchy={['kk']} openShortcutsHelp={openShortcutsHelp} onStoryFilter={onStoryFilter} /> )) .add('storiesHierarchies exists but is empty', () => ( <StoriesPanel storiesHierarchies={createHierarchies([])} openShortcutsHelp={openShortcutsHelp} onStoryFilter={onStoryFilter} /> ));
src/components/Menu/Home.js
shierby/storehome
import React from 'react'; class Home extends React.Component { render() { return ( <div className="container-fluid catalog_page"> <div className="container"> <h1>Home Page</h1> </div> </div> ) } } export default Home;
www/src/components/survey/SurveyUserList.js
cygwin255/SimpleSurvey
import React from 'react' import Pagination from 'components/navigation/Pagination' import { Link } from 'react-router-dom' import { debounce } from 'lodash' class SurveyUserList extends React.Component { componentWillMount () { this.setSearch = debounce(this.setSearch, 250) } setSearch (value) { this.setState({search: value}) this.props.update(this.props.page, value) } render () { let { update, page, pages, surveys, total } = this.props return ( <div> <div className='d-flex justify-content-between'> <input className='form-control font-control-sm width-300 margin-bottom' placeholder='Search: All' onChange={(e) => this.setSearch(e.target.value)} /> <h5> Total surveys: {total} </h5> </div> <table className='table table-hover surveys'> <thead> <tr> <th>Name</th> <th>Created</th> <th>Pages</th> <th>Questions</th> <th>Url to pass</th> </tr> </thead> <tbody> {surveys && surveys.map((survey, index) => <tr key={index}> <th>{survey.name}</th> <td>{survey.changed}</td> <td>{survey.pages}</td> <td>{survey.questions}</td> <td> <Link to={`/survey/pass/${survey.id}/${survey.token}`}> Link to survey </Link> </td> </tr> )} </tbody> </table> <Pagination changePage={(page) => update(page, this.state.search)} page={page} pages={pages} /> </div> ) } } export default SurveyUserList
app/javascript/flavours/glitch/features/search/index.js
im-in-space/mastodon
import React from 'react'; import SearchContainer from 'flavours/glitch/features/compose/containers/search_container'; import SearchResultsContainer from 'flavours/glitch/features/compose/containers/search_results_container'; const Search = () => ( <div className='column search-page'> <SearchContainer /> <div className='drawer__pager'> <div className='drawer__inner darker'> <SearchResultsContainer /> </div> </div> </div> ); export default Search;
src/pages/index.js
getinsomnia/website
import React from 'react'; import DownloadLink from '../components/download-link'; import DownloadButton from '../components/download-button'; import SocialCards from '../components/social-cards'; import Link from '../components/link'; import Companies from '../partials/companies'; import Helmet from 'react-helmet'; import { site as config } from '../config'; // SVGs import iconDownload from '../assets/icons/icn-download.svg'; import logoCore from '../assets/logos/logo-core-hero-28x.svg'; import logoDesigner from '../assets/logos/logo-designer-hero-28x.svg'; import illustrationCore from '../assets/illustration-insomnia-client.svg'; import illustrationDesigner from '../assets/illustration-insomnia-designer.svg'; export default () => ( <React.Fragment> <Helmet> <title>{config.name} | The API Design Platform and REST Client</title> <body data-navbar="floating" /> </Helmet> <SocialCards title="Insomnia" summary="Design & Debug APIs like a human, not a robot" isBanner /> <div className="jumbotron"> <div className="jumbotron-inner"> <div className="slogan container"> <div className="row"> <div className="col-12"> <h1 className="font-regular"> Design, debug, and test APIs like a <u>human</u>, not a robot. </h1> <h2 className="font-light">Finally, a workflow you'll love.</h2> </div> </div> </div> <div className="product-offerings container"> <div className="row"> <div className="col-6 offering"> <div className="graphic"> <DownloadLink> <img src={illustrationDesigner} /> </DownloadLink> </div> <h3 className="font-regular"> <img src={logoDesigner} className="icon" /> <span>Insomnia Designer</span> </h3> <p> The Collaborative API Design Tool for designing, testing and managing OpenAPI specifications. </p> <DownloadButton> <img src={iconDownload} className="icon" alt="Download" />{' '} Latest Release <span className="badge">New</span> </DownloadButton> <p className="latest-version"> <small> <Link to={`/changelog`}>Changelog</Link> </small> </p> </div> <div className="col-6 offering"> <div className="graphic"> <DownloadLink> <img src={illustrationCore} /> </DownloadLink> </div> <h3 className="font-regular"> <img src={logoCore} className="icon" /> <span>Insomnia Core</span> </h3> <p> The Desktop API client for REST and GraphQL. Make requests, inspect responses. </p> <DownloadButton> <img src={iconDownload} className="icon" alt="Download" />{' '} Latest Release </DownloadButton> <p className="latest-version"> <small> <Link to={`/changelog`}>Changelog</Link> </small> </p> </div> </div> </div> </div> </div> <main role="main"> <section className="no-margin padding-top-lg padding-bottom-lg"> <div className="container"> <div className="row"> <div className="col-12 center"> <h2 className="text-xl">Design, Test, and Deploy APIs</h2> <p>Workflows and Tools to make API Development Easier</p> </div> </div> <div className="row row-center-y"> <div className="col-4"> <img src={logoCore} className="icon icon-bg" /> <h3 className="text-md">Create Requests</h3> <p> Quickly create and group requests, specify environment variables, authentication, generate code snippets, and more... </p> <p> <Link to={`/products/core`}>Insomnia Core &rarr;</Link> </p> </div> <div className="col-4"> <img src={logoCore} className="icon icon-bg" /> <h3 className="text-md">View Responses</h3> <p> Get all the details on responses. View the whole request timeline, status codes, body, headers, cookies, and more. </p> <p> <Link to={`/products/core`}>Insomnia Core &rarr;</Link> </p> </div> <div className="col-4"> <img src={logoCore} className="icon icon-bg" /> <h3 className="text-md">Organize Everything</h3> <p> Create workspaces, folders, environments, drag-and-drop requests, and easily import and export your data. </p> <p> <Link to={`/products/core`}>Insomnia Core &rarr;</Link> </p> </div> </div> <div className="row row-center-y"> <div className="col-4"> <img src={logoDesigner} className="icon icon-bg" /> <h3 className="text-md">Design APIs</h3> <p> Create, edit, lint, debug, preview, and manage all of your OpenAPI specs in one collaborative API design editor. </p> <p> <Link to={`/products/designer`}>Insomnia Designer &rarr;</Link> </p> </div> <div className="col-4"> <img src={logoDesigner} className="icon icon-bg" /> <h3 className="text-md">Configure Gateways</h3> <p> Generate configuration for common API gateways such as the Kong API Gateway, and Kong for Kubernetes. </p> <p> <Link to={`/products/designer`}>Insomnia Designer &rarr;</Link> </p> </div> <div className="col-4"> <img src={logoDesigner} className="icon icon-bg" /> <h3 className="text-md">Deploy Specs</h3> <p> Sync your API designs with source control such as Github / Gitlab, and deploy directly to API Gateways such as Kong with one click. </p> <p> <Link to={`/products/designer`}>Insomnia Designer &rarr;</Link> </p> </div> </div> <div className="row row-center-y"> <div className="col-4"> <img src={logoDesigner} className="icon icon-bg" /> <h3 className="text-md">Test APIs</h3> <p> Write unit tests for your Insomnia debug requests using JavaScript, to be ran in app or terminal using Inso. </p> <p> <Link to={`/products/designer`}>Insomnia Designer &rarr;</Link> </p> </div> </div> </div> </section> <section className="light no-margin padding-bottom-lg padding-top-lg"> <div className="container"> <div className="row"> <div className="col-12 center"> <h2>More than 800,000 developers trust Insomnia</h2> <div className="padding-top"> <Companies /> <br /> <br /> <DownloadButton className="button--big"> Download </DownloadButton> &nbsp;&nbsp; <Link to="/teams" className="button button--big button--no-outline"> Teams Edition </Link> </div> </div> </div> </div> </section> <section className="dark no-margin padding-bottom-lg padding-top-lg"> <div className="container"> <div className="row"> <div className="col-12 center"> <h2 className="text-xl">Still not convinced?</h2> <p>Maybe this big ol' list of features will help</p> </div> </div> <div className="row feature-list"> <div className="col-6"> <ul> <li> <Link to="/graphql/">GraphQL</Link> support </li> <li>OAuth 1.0 and 2.0 auth</li> <li>Multipart form builder</li> <li>Query parameter builder</li> <li>Plugin System</li> <li>SSL client certificates</li> <li>JSONPath and XPath</li> <li>Response history</li> <li>Data import/export</li> <li>Rendered HTML preview</li> <li>Image and SVG preview</li> <li>AWS authentication</li> <li>Configurable proxy</li> <li>Color themes</li> <li>Cloud sync and sharing</li> </ul> </div> <div className="col-6"> <ul> <li> Import from <code style={{ color: '#333' }}>curl</code> </li> <li>Digest, Basic, NTLM Auth</li> <li>Nunjucks templating</li> <li>Configurable timeout</li> <li>HAR import</li> <li>Swagger import</li> <li>Request filtering</li> <li>Toggle SSL validation</li> <li>Keyboard shortcuts</li> <li>Usable at almost all sizes</li> <li>NTLM authentication</li> <li>Responsive interface</li> <li>Autocomplete Hints</li> <li>Redirect chain visualization</li> <li>Mac, Windows and Linux</li> </ul> </div> </div> <br /> <div className="center"> <p>Go on, give it a try. You won't regret it.</p> <br /> <DownloadButton className="button--big" /> </div> <br /> </div> </section> </main> </React.Fragment> );
src/Stateful.js
rongierlach/react-web3-network-status
import React from 'react' import { Provider } from 'react-redux' import store from './state/store' import NetworkStatus from './NetworkStatus' const ReactWeb3NetworkStatus = props => ( <Provider store={store}> <NetworkStatus {...props} /> </Provider> ) export default ReactWeb3NetworkStatus
src/components/Disqus/Disqus.js
Grusteam/spark-in-me
import React from 'react'; import ReactDOM from 'react-dom'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import cx from 'classnames'; import s from './Disqus.css'; import ReactDisqusComments from '../../../node_modules/react-disqus-comments'; class Disqus extends React.Component { handleNewComment(comment) { console.log(comment.text); } render() { const alias = this.props.data.alias, disqusUrl = this.props.data.disqusUrl, disqus = `<div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://http-spark-in-me.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>`; const props = { shortname: 'http-spark-in-me', identifier: alias, url: disqusUrl, onNewComment: this.handleNewComment } return ( <ReactDisqusComments {...props} className={s.disqus}/> ); } } export default withStyles(s)(Disqus);
app/test/unexpectedWithAddons.js
gustavnikolaj/keepass-reader
import unexpected from 'unexpected' import unexpectedReactShallow from 'unexpected-react-shallow' import React from 'react' export var expectForComponents = unexpected .clone() .use(unexpectedReactShallow) .addAssertion('to render as', (expect, subject, value) => { var renderer = React.addons.TestUtils.createRenderer() renderer.render(subject) return expect(renderer, 'to have rendered', value) })
app/public-src/components/player/player.js
SpaceAppsReno/higher-ground
import classes from 'app-utils/classes'; import styles from './player.scss'; import React, { Component } from 'react'; import Icon from 'app-components/icon/icon'; import Button from 'app-components/button/button'; export default class Player extends Component { static propTypes = { year: React.PropTypes.number.isRequired, min: React.PropTypes.number.isRequired, max: React.PropTypes.number.isRequired, presenting: React.PropTypes.bool.isRequired, onYear: React.PropTypes.func.isRequired, onPresent: React.PropTypes.func.isRequired, }; constructor() { super(); this.state = { hidden: false, looper: false, }; } handleChange = ({ target: { value: year } }) => { this.props.onYear(parseInt(year)); } render() { return ( <div className={classes(styles.main, { [styles.moveDown]: this.state.hidden }) }> <Icon className={classes(styles.reducBtn, styles.btn, { [styles.flip]: this.state.hidden }) } name='sort-down' onClick={ () => this.setState({ hidden: !this.state.hidden }) } ></Icon> <div className={styles.year}> {this.props.year} </div> <div> <input className={styles.slider} type="range" value={this.props.year} min={this.props.min} max={this.props.max} onInput={this.handleChange} step={1} /> </div> <div className={styles.controls}> <Icon className={classes(styles.control, styles.btn)} name='backward' onClick={() => { this.props.onYear(parseInt(this.props.year - 1)); }}/> <Icon className={classes(styles.control, styles.btn)} name={'play'} onClick={ () => { // let that = this; // if (this.state.playing) { // clearInterval(looper); // console.log(this.state.playing, looper); // return; // } this.setState({ playing: !this.state.playing }); this.state.looper = setInterval(() => { this.props.onYear(parseInt(this.props.year + 1)); if (this.props.year > 2099) { clearInterval(this.state.looper); this.state.looper = false; } }, 1000); }}/> <Icon className={classes(styles.control, styles.btn)} name='stop' onClick={() => { if (this.state.looper) { clearInterval(this.state.looper); this.state.looper = false; } }}/> <Icon className={classes(styles.control, styles.btn)} name='forward' onClick={() => { this.props.onYear(parseInt(this.props.year + 1)); }}/> <Button className={styles.presentation} onClick={() => { this.props.onPresent(true); }}>Presentation Mode</Button> </div> </div> ); } }
src/routes.js
davide-ravasi/redux-firebase
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import MenuTop from './components/menu_top'; //import PostItem from './components/post_item'; import PostList from './components/post_list'; import PostsNew from './components/create_form'; import PostMod from './components/modify_form'; export default( <Route path="/" component={App}> <IndexRoute component={PostList} /> <Route path="create" component={PostsNew} /> <Route path="modif/(:postId)" component={PostMod} /> </Route> )
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
ketoo/actor-platform
import _ from 'lodash'; import Immutable from 'immutable'; import keymirror from 'keymirror'; import React from 'react'; import { Styles, TextField, FlatButton } from 'material-ui'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import ContactStore from 'stores/ContactStore'; import ContactItem from './ContactItem.react'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); const STEPS = keymirror({ NAME_INPUT: null, CONTACTS_SELECTION: null }); class CreateGroupForm extends React.Component { static displayName = 'CreateGroupForm' static childContextTypes = { muiTheme: React.PropTypes.object }; state = { step: STEPS.NAME_INPUT, selectedUserIds: new Immutable.Set() } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7' } }); } render() { let stepForm; switch (this.state.step) { case STEPS.NAME_INPUT: stepForm = ( <form className="group-name" onSubmit={this.onNameSubmit}> <div className="modal-new__body"> <TextField className="login__form__input" floatingLabelText="Group name" fullWidth onChange={this.onNameChange} value={this.state.name}/> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Add members" secondary={true} type="submit"/> </footer> </form> ); break; case STEPS.CONTACTS_SELECTION: let contactList = _.map(ContactStore.getContacts(), (contact, i) => { return ( <ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/> ); }); stepForm = ( <form className="group-members" onSubmit={this.onMembersSubmit}> <div className="count">{this.state.selectedUserIds.size} Members</div> <div className="modal-new__body"> <ul className="contacts__list"> {contactList} </ul> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Create group" secondary={true} type="submit"/> </footer> </form> ); break; } return stepForm; } onContactToggle = (contact, isSelected) => { if (isSelected) { this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)}); } else { this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)}); } } onNameChange = event => { event.preventDefault(); this.setState({name: event.target.value}); } onNameSubmit = event => { event.preventDefault(); if (this.state.name) { let name = this.state.name.trim(); if (name.length > 0) { this.setState({step: STEPS.CONTACTS_SELECTION}); } } } onMembersSubmit =event => { event.preventDefault(); CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS()); } } export default CreateGroupForm;
source/components/main-menu.js
Aokibi/Regents-Navigation
import React from 'react' import {Link} from 'react-router' import Button from './button' import styles from './our-styles.less' /* The main menu page. */ class MainMenu extends React.Component { render() { return ( <div> <div> <h1 className ={styles['heading']}> Welcome to the St. Olaf Regents Navigation System</h1> </div> <div> <h3 className={styles['main-menu']}> Main Menu </h3> </div> <div> <Link to='/createnewnavigation'><Button>Start New Navigation</Button></Link><br/> <Link to='/savednavigationscreen'><Button>Start Saved Navigation</Button></Link><br/> <Link to='/settings'><Button>Settings</Button></Link><br/> <Link to='/mainmenuhelp'><Button>Help</Button></Link><br/> <Link to='/about'><Button>About</Button></Link><br/> </div> </div> ) } } export default MainMenu
components/background-images.js
WanderlandTravelers/wanderlandtravelers.github.io
import React from 'react' import Slider from 'react-slick' import responsiveImages from './responsive-images.js' import {Icon} from 'react-fa' import '../css/background-images' // import 'slick-carousel/slick/slick.scss' // import 'slick-carousel/slick/slick-theme.scss' export default class BackgroundImages extends React.Component { constructor (props) { super(props) this.state = this.updatedDimensions() this.updateDimensions = this.updateDimensions.bind(this) this.updatedDimensions = this.updatedDimensions.bind(this) this.fullscreenClass = this.fullscreenClass.bind(this) this.fullscreenBUtton = this.fullscreenButton.bind(this) this.hideBUtton = this.hideButton.bind(this) } componentDidMount () { window.addEventListener('resize', this.updateDimensions) } componentWillUnmount () { window.removeEventListener('resize', this.updateDimensions) } updatedDimensions () { return { width: typeof(window) === 'undefined' ? null : window.innerWidth, height: typeof(window) === 'undefined' ? null : window.innerHeight } } updateDimensions () { this.setState(this.updatedDimensions()) } isMoreLandscapey (img) { return (img.width / img.height) > (this.state.width / this.state.height) } isFullScreen () { return typeof(document) !== 'undefined' && document.webkitIsFullScreen } fullscreenButton () { return ( <a id="fullscreen" className={this.fullscreenClass()} onClick={this.props.goFullscreen} > <Icon name="arrows-alt"/> </a> ) } hideButton () { if (!this.isFullScreen()) { return ( <a id="hide-content" onClick={this.props.handleHideContent}> <Icon name={this.props.hide ? 'eye' : 'eye-slash'}/> </a> ) } return } fullscreenClass () { return this.isFullScreen() ? 'fullscreen' : '' } render () { const settings = { dots: false, infinite: true, pauseOnHover: false, speed: 2000, slidesToShow: 1, slidesToScroll: 1, fade: true, lazyLoad: 'progressive', arrows: true, dots: false, autoplay: true, autoplaySpeed: 25000, } return ( <div id="background-images" className={this.fullscreenClass()}> <Slider {...settings}> {responsiveImages.map((image, i) => ( <div key={i} className="responsive-background-image"> <img srcSet={image.srcset} src={image.src} width={this.isMoreLandscapey(image.images[0]) ? '100%' : 'auto'} height={this.isMoreLandscapey(image.images[0]) ? 'auto' : '100%'} /> <img className="blurred-image" srcSet={image.srcset} src={image.src} /> </div> ))} </Slider> {this.fullscreenButton()} {this.hideButton()} </div> ) } }
src/client/index.js
mdang8/IsTheMatrixOn
import 'bootstrap'; import React from 'react'; import { render } from 'react-dom'; import Main from './components/Main.jsx'; import './scss/app.scss'; // only renders the main React component if the "root" element is present if (document.getElementById('root')) { render(<Main />, document.getElementById('root')); }
packages/core/src/icons/components/CtbcDirect.js
iCHEF/gypcrete
import React from 'react'; export default function SvgCtbcDirect(props) { return ( <svg width="1em" height="1em" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M656.3 843.8H343.8c-34.6 0-62.5-28-62.5-62.5V218.8c0-34.6 27.9-62.5 62.5-62.5h312.5c34.5 0 62.5 27.9 62.5 62.5v562.5c0 34.5-28 62.5-62.5 62.5zm-296.9-625c-8.7 0-15.6 6.9-15.6 15.6v531.2c0 8.7 6.9 15.7 15.6 15.7h281.2c8.7 0 15.7-7 15.7-15.7V234.4c0-8.7-7-15.6-15.7-15.6H359.4zm109.3 515.6c0-8.7 6.7-15.6 15.8-15.6h30.9c8.7 0 15.8 7.2 15.8 15.6 0 8.6-6.7 15.6-15.8 15.6h-30.9c-8.8 0-15.8-7.2-15.8-15.6zm156.2-46.9h-250V281.3h250v406.2zM421.8 531.3c-8.6 0-15.6 6.9-15.6 15.6 0 8.6 7 15.6 15.6 15.6h62.5v15.6c0 8.7 7 15.7 15.6 15.7 8.7 0 15.7-7 15.7-15.7v-15.6h62.5c8.6 0 15.6-7 15.6-15.6v-62.5c0-8.7-7-15.6-15.6-15.6h-62.5v-31.3h62.5c8.6 0 15.6-7 15.6-15.6 0-8.7-7-15.6-15.6-15.6h-62.5v-15.7c0-8.6-7-15.6-15.7-15.6-8.6 0-15.6 7-15.6 15.6v15.7h-62.5c-8.6 0-15.6 6.9-15.6 15.6v62.5c0 8.6 7 15.6 15.6 15.6h62.5v31.3h-62.5zm140.6 0h-46.8V500h46.8v31.3zm-78.1-62.5h-46.9v-31.3h46.9v31.3z" /> </svg> ); }
modules/Redirect.js
shunitoh/react-router
import PropTypes from 'prop-types' import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { formatPattern } from './PatternUtils' import { falsy } from './InternalPropTypes' /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ const Redirect = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.from) route.path = route.from route.onEnter = function (nextState, replace) { const { location, params } = nextState let pathname if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params) } else if (!route.to) { pathname = location.pathname } else { let routeIndex = nextState.routes.indexOf(route) let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1) let pattern = parentPattern.replace(/\/*$/, '/') + route.to pathname = formatPattern(pattern, params) } replace({ pathname, query: route.query || location.query, state: route.state || location.state }) } return route }, getRoutePattern(routes, routeIndex) { let parentPattern = '' for (let i = routeIndex; i >= 0; i--) { const route = routes[i] const pattern = route.path || '' parentPattern = pattern.replace(/\/*$/, '/') + parentPattern if (pattern.indexOf('/') === 0) break } return '/' + parentPattern } }, propTypes: { path: PropTypes.string, from: PropTypes.string, // Alias for path to: PropTypes.string.isRequired, query: PropTypes.object, state: PropTypes.object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Redirect> elements are for router configuration only and should not be rendered' ) } }) export default Redirect
src/health/User.js
wangboy/health-client
/** * Created by wangbo on 23/04/2017. */ // in src/users.js import React from 'react'; import {List, Datagrid, EmailField, TextField} from 'admin-on-rest/lib/mui'; export const UserList = (props) => ( <List title="All users" {...props}> <Datagrid> <TextField source="id"/> <TextField source="name"/> <TextField source="username"/> <EmailField source="email"/> </Datagrid> </List> );
src/svg-icons/file/folder-shared.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileFolderShared = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z"/> </SvgIcon> ); FileFolderShared = pure(FileFolderShared); FileFolderShared.displayName = 'FileFolderShared'; FileFolderShared.muiName = 'SvgIcon'; export default FileFolderShared;
src/docs/components/tiles/TilesDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Tiles from 'grommet/components/Tiles'; import Tile from 'grommet/components/Tile'; import Anchor from 'grommet/components/Anchor'; import Button from 'grommet/components/Button'; import DocsArticle from '../../../components/DocsArticle'; export const DESC = (<span> A grid of items. The preferred method of populating Tiles is to use Tile children. </span>); const ONCLICK_EXAMPLE = `onClick={this._onClick.bind(this, id)}`; export default class TileDoc extends Component { render () { return ( <DocsArticle title='Tiles' action={ <Button primary={true} path='/docs/tiles/examples' label='Examples' /> }> <section> <p>{DESC}</p> <Tiles flush={false}> <Tile pad='medium' size='small' colorIndex='light-2'>Tile</Tile> <Tile pad='medium' size='small' colorIndex='light-2'>Tile</Tile> <Tile pad='medium' size='small' colorIndex='light-2'>Tile</Tile> </Tiles> </section> <section> <h2>Tiles Properties</h2> <dl> <dt><code>fill true|false</code></dt> <dd>Whether the contents expand to fill all of the available space.</dd> <dt><code>flush true|false</code></dt> <dd>Whether the contents are flush with the left and right edges or not. Defaults to true. When flush, there is no padding around the outside or between the contained tiles.</dd> <dt><code>onMore {'{function}'}</code></dt> <dd>Function that will be called when more data is needed.</dd> <dt><code>onSelect {'{function (selected)}'}</code></dt> <dd>Function that will be called when the user selects something. When only one item is selected, it returns the zero based index for that item. When multiple items are selected, it returns an array of those {'item\'s'} zero based indexes.</dd> <dt><code>selectable true|false|multiple</code></dt> <dd>Whether rows are selectable. <code>multiple</code> indicates that multiple rows may be selected</dd> <dt><code>selected {'{number}|[{number}, ...]'}</code></dt> <dd>The currently selected item(s) using a zero based index.</dd> <dt><code>size small|medium|large</code></dt> <dd>The width of the contained tiles. Defaults to <code>medium</code>.</dd> </dl> <p>Properties for <Anchor path='/docs/box'>Box</Anchor> are also available for Tiles.</p> </section> <section> <h2>Tile Properties</h2> <dl> <dt><code>onClick {'{function}'}</code></dt> <dd>Called when the user clicks on the item. Callers should bind an identifier to the function to distinguish between multiple items. For example <code>{ONCLICK_EXAMPLE}</code></dd> <dt><code>selected true|false</code></dt> <dd>Whether this item is currently selected.</dd> <dt><code>wide true|false</code></dt> <dd>Whether the tile should fill the full width of the Tiles component that contains it.</dd> </dl> <p>Properties for <Anchor path='/docs/box'>Box</Anchor> are also available for Tile.</p> </section> </DocsArticle> ); } };
examples/huge-apps/components/GlobalNav.js
KamilSzot/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); console.log(styles.link); export default GlobalNav;
web/src/app/components/user/items.js
yacloud-io/teleport
import React from 'react'; const U2F_ERROR_CODES_URL = 'https://developers.yubico.com/U2F/Libraries/Client_error_codes.html'; export const ErrorMessage = ({ message }) => { message = message || ''; if(message.indexOf('U2F') !== -1 ) { return ( <label className="grv-invite-login-error"> {message} <br /> <small className="grv-invite-login-error-u2f-codes"> <span>click <a target="_blank" href={U2F_ERROR_CODES_URL}>here</a> to learn more about U2F error codes </span> </small> </label> ) } return ( <label className="error">{message} </label> ) }
examples/redux-observable/cancellable-counter/src/components/Counter.js
ioof-holdings/redux-subspace
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { INCREMENT, DECREMENT, INCREMENT_IF_ODD, CANCEL_INCREMENT_ASYNC, START_COUNTDOWN } from '../actionTypes' function Counter({counter, countdown, dispatch}) { const action = (type, value) => () => dispatch({type, value}) return ( <div> Clicked: {counter} times {' '} <button onClick={action(INCREMENT)}>+</button> {' '} <button onClick={action(DECREMENT)}>-</button> {' '} <button onClick={action(INCREMENT_IF_ODD)}>Increment if odd</button> {' '} <button onClick={countdown ? action(CANCEL_INCREMENT_ASYNC) : action(START_COUNTDOWN)} style={{color: countdown ? 'red' : 'black'}}> {countdown ? `Cancel increment (${countdown})` : 'increment after 5s'} </button> </div> ) } Counter.propTypes = { // dispatch actions dispatch: PropTypes.func.isRequired, // state counter: PropTypes.number.isRequired, countdown: PropTypes.number.isRequired } function mapStateToProps(state) { return { counter: state.counter, countdown: state.countdown } } export default connect(mapStateToProps)(Counter)
src/svg-icons/editor/insert-emoticon.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertEmoticon = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); EditorInsertEmoticon = pure(EditorInsertEmoticon); EditorInsertEmoticon.displayName = 'EditorInsertEmoticon'; EditorInsertEmoticon.muiName = 'SvgIcon'; export default EditorInsertEmoticon;
examples/async/index.js
linalu1/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
src/svg-icons/hardware/computer.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareComputer = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z"/> </SvgIcon> ); HardwareComputer = pure(HardwareComputer); HardwareComputer.displayName = 'HardwareComputer'; HardwareComputer.muiName = 'SvgIcon'; export default HardwareComputer;
src/Choropleth.js
ornl-sava/vis-react-components
import React from 'react' import PropTypes from 'prop-types' import { TransitionGroup } from 'react-transition-group' import { interpolate, geoPath, geoEquirectangular } from 'd3' import * as topojson from 'topojson' import { setEase } from './util/d3' import SVGComponent from './SVGComponent' class Choropleth extends React.Component { constructor (props) { super(props) this.projection = geoEquirectangular() this.path = geoPath() .projection(this.projection) this.getDatum = this.getDatum.bind(this) this.onClick = this.onClick.bind(this) this.onEnter = this.onEnter.bind(this) this.onLeave = this.onLeave.bind(this) this.onMove = this.onMove.bind(this) } getDatum (id) { // Get datum based on id let index = -1 this.props.data.forEach((d, i) => { if (d[this.props.keyField] === id) { index = i return false } }) return this.props.data[index] } onClick (event) { let target = event.target let id = target.getAttribute('data-id') this.props.onClick(event, this.getDatum(id)) } onEnter (event) { let target = event.target let id = target.getAttribute('data-id') this.props.onEnter(event, this.getDatum(id)) } onLeave (event) { let target = event.target let id = target.getAttribute('data-id') this.props.onLeave(event, this.getDatum(id)) } onMove (event) { let target = event.target let id = target.getAttribute('data-id') this.props.onMove(event, this.getDatum(id)) } render () { // Get map bounds and scaling let mapBounds = this.path.bounds(topojson.feature(this.props.map, this.props.map.objects.countries)) let mapScale = this.projection.scale() // Get possible scales based on width / height let hscale = mapScale * this.props.chartWidth / (mapBounds[1][0] - mapBounds[0][0]) let vscale = mapScale * this.props.chartHeight / (mapBounds[1][1] - mapBounds[0][1]) // Determine which scaling to use mapScale = (hscale < vscale) ? hscale : vscale this.projection .scale(mapScale) .translate([this.props.chartWidth / 2, this.props.chartHeight / 2]) this.path .projection(this.projection) // Helper to get datum and return color const getColor = (id) => { // Find associated datum let index = -1 this.props.data.forEach((d, i) => { if (d[this.props.keyField] === id) { index = i return false } }) let datum = this.props.data[index] let color = this.props.unselectedColorScale.range()[0] if (typeof datum !== 'undefined') { if (datum[this.props.selectedField] === this.props.selectedValue) { color = datum[this.props.valueField] === 0 ? this.props.selectedColorScale.range()[0] : this.props.selectedColorScale(datum[this.props.valueField]) } else { color = datum[this.props.valueField] === 0 ? this.props.unselectedColorScale.range()[0] : this.props.unselectedColorScale(datum[this.props.valueField]) } } return color } return ( <g> <TransitionGroup component='g'> {topojson.feature(this.props.map, this.props.map.objects.countries).features.map((d, i) => { return ( <SVGComponent Component='path' key={i} data-id={d.id} d={this.path(d, i)} fill={getColor(d.id)} onEnter={{ func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attrTween('fill', () => { return interpolate(this.props.unselectedColorScale.range()[0], props.fill) }) return transition } }} onUpdate={{ func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('fill', props.fill) .attr('d', props.d) return transition } }} onClick={this.onClick} onMouseEnter={this.onEnter} onMouseLeave={this.onLeave} onMouseMove={this.onMove} /> ) })} </TransitionGroup> <g> <SVGComponent Component='path' className='boundary' onUpdate={{ func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('d', props.d) return transition } }} d={this.path(topojson.mesh(this.props.map, this.props.map.objects.countries, (a, b) => { return a !== b }))} /> </g> </g> ) } } Choropleth.defaultProps = { data: [], keyField: 'key', valueField: 'value', selectedField: 'selectedField', selectedValue: 'selected', onClick: () => {}, onEnter: () => {}, onLeave: () => {}, onMove: () => {} } Choropleth.propTypes = { selectedColorScale: PropTypes.func, unselectedColorScale: PropTypes.func, map: PropTypes.object.isRequired, data: PropTypes.array, chartWidth: PropTypes.number, chartHeight: PropTypes.number, keyField: PropTypes.string, valueField: PropTypes.string, selectedField: PropTypes.string, selectedValue: PropTypes.string, onClick: PropTypes.func, onEnter: PropTypes.func, onLeave: PropTypes.func, onMove: PropTypes.func } export default Choropleth
src/components/common/articles/ArticleSummary.js
ESTEBANMURUZABAL/my-ecommerce-template
/** * Imports */ import React from 'react'; import {FormattedMessage} from 'react-intl'; import {Link} from 'react-router'; import {slugify} from '../../../utils/strings'; // Flux import IntlStore from '../../../stores/Application/IntlStore'; // Required components import Heading from '../typography/Heading'; import Text from '../typography/Text'; // Translation data for this component import intlData from './ArticleSummary.intl'; /** * Component */ class ArticleSummary extends React.Component { static contextTypes = { getStore: React.PropTypes.func.isRequired }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./ArticleSummary.scss'); } //*** Template ***// render() { // // Helper methods & variables // let intlStore = this.context.getStore(IntlStore); let routeParams = {locale: intlStore.getCurrentLocale()}; // Base route params let articleRouteParams = Object.assign({ contentId: this.props.content.id, contentSlug: slugify(intlStore.getMessage(this.props.content.name)) }, routeParams); let headingSize = 'medium'; if (['small', 'large'].indexOf(this.props.size) !== -1) { headingSize = this.props.size; } let showReadMore = this.props.content.body.markdown && this.props.content.body.markdown[intlStore.getCurrentLocale()] && this.props.content.body.markdown[intlStore.getCurrentLocale()] !== '' && !this.props.hideLink; // // Return // return ( <div className="article-summary"> <Heading size={headingSize}> <FormattedMessage message={intlStore.getMessage(this.props.content.name)} locales={intlStore.getCurrentLocale()} /> </Heading> <div className="article-summary__content"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(this.props.content.body.summary)} locales={intlStore.getCurrentLocale()} /> {showReadMore ? <Link className="article-summary__link" to="article-slug" params={articleRouteParams}> <FormattedMessage message={intlStore.getMessage(intlData, 'readMore')} locales={intlStore.getCurrentLocale()} /> <i className="fa fa-file-text-o" aria-hidden="true" /> </Link> : null } </Text> </div> </div> ); } } /** * Exports */ export default ArticleSummary;
react/gameday2/components/embeds/EmbedUstream.js
nwalters512/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedUstream = (props) => { const channel = props.webcast.channel const src = `https://www.ustream.tv/embed/${channel}?html5ui=1` return ( <iframe width="100%" height="100%" src={src} scrolling="no" allowFullScreen frameBorder="0" style={{ border: '0 none transparent' }} /> ) } EmbedUstream.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedUstream
src/containers/Info.js
ComicsReader/reader
import React, { Component } from 'react'; import NavigationSidebar from 'components/NavigationSidebar'; export default class Info extends Component { onClick = (event) => { if (window.PLATFORM === 'electron') { event.preventDefault(); const { shell } = require('electron'); shell.openExternal(event.target.href); return false; } else { return true; } } render() { return( <div style={{overflow: 'hidden', paddingLeft: 95, color: 'white', height: '100%'}}> <NavigationSidebar highlightTag="info" /> <h2>About</h2> <p> ComicsReader 是一個基於 React/Redux/Electron 等網頁技術構建的漫畫閱讀器。漫畫來源來自 DM5,前身為 <a href="https://github.com/zeroshine/ComicsScroller" target="_blank" onClick={this.onClick}>ComicsScroller</a> 這款 Chrome Extension,本軟體作者基於其原始碼重新建構。 </p> <h2>Source Code</h2> <p> GitHub: <a href="https://github.com/ComicsReader/app" target="_blank" onClick={this.onClick}>https://github.com/ComicsReader/app</a> </p> <p>The MIT License (MIT)</p> <p>Copyright (c) 2016 Yukai Huang</p> <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p> <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p> <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p> </div> ); } }
src/stories/index.js
brandai/brandai-storybook
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import Button from '../components/Button'; storiesOf('Button', module) .add('default view', () => ( <Button onClick={ action('button clicked') }>Hello</Button> )) .add('some emojies as the text', () => ( <Button>😀 😎 👍 💯</Button> )) .add('custom styles', () => { const style = { fontSize: 20, textTransform: 'uppercase', color: '#FF8833', }; return ( <Button style={ style }>Hello</Button> ); });
client/components/Flass/Lecture/Analysis/Analysis.js
Nexters/flass
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import PropTypes from 'prop-types'; import _ from 'lodash'; import ChartComponent from './Chart/ChartComponent'; import SingleChoiceComponent from './SingleChoice/SingleChoiceComponent'; import AnalysisTabItemComponent from './AnalysisTabItem/AnalysisTabItemComponent'; import { AnalysisLoadingHOC } from './AnalysisLoadingHOC'; import { AnalysisFetchHOC } from './AnalysisFetchHOC'; import { AnalysisMapAnswersHOC } from './AnalysisMapAnswersHOC'; import { AnalysisStyled } from './AnalysisStyled'; import { REQUEST_LECTURE_ANALYSIS, UNMOUNT_ANALYSIS } from '~/ducks/Flass/analysises'; const { Tab, Wrapper, Header, Body, Row, Title, Col5, ChartTextWrapper, ChartTextTitle, ChartTextNumber } = AnalysisStyled; const { string, func, arrayOf, shape, number } = PropTypes; const propTypes = { updateLectureAnalysis: func.isRequired, questionIndex: number.isRequired, questions: arrayOf(shape({ id: number, content: string, correct_answer: string, question_at: number })).isRequired, question: shape({ id: number, content: string, correct_answer: string, question_at: number }).isRequired, answers: arrayOf(shape({ id: number, user_id: number, question_id: number, answer: string, created_at: string, updated_at: string })).isRequired }; const defaultProps = {}; class Analysis extends Component { render() { const { answers, questionIndex, question } = this.props; return ( <Wrapper> <Header> {this._renderQuestionTabs()} </Header> <Body> <Row> <Title> {`Q${questionIndex + 1}. ${question.content}`} </Title> </Row> <Row marginTop> <Col5> <ChartTextWrapper> <ChartTextTitle> 퀴즈 완료 학생 수 </ChartTextTitle> <ChartTextNumber> {`${answers.length}명`} </ChartTextNumber> </ChartTextWrapper> {this._renderChart()} </Col5> <Col5> {this._renderSingleChoices(question)} </Col5> </Row> </Body> </Wrapper> ); } _renderQuestionTabs = () => ( <Tab> {this._renderQuestionTab()} </Tab> ) _renderQuestionTab = () => { const { questions, questionIndex } = this.props; return _.map(questions, (question, index) => ( <AnalysisTabItemComponent key={question.id} isActive={index === questionIndex} questionId={question.id} questionIndex={index} handleSelect={this._handleSelect} /> )); } _handleSelect = index => { this.props.updateLectureAnalysis(index); } _renderChart = () => { const { usersOfAnswers } = this.props; const labels = usersOfAnswers.map(usersOfAnswer => usersOfAnswer.answer); const data = usersOfAnswers.map(usersOfAnswer => usersOfAnswer.userAnswers.length); return (<ChartComponent labels={labels} data={data} />); }; _renderSingleChoices = question => { const { usersOfAnswers } = this.props; return usersOfAnswers.map(usersOfAnswer => (<SingleChoiceComponent key={usersOfAnswer.id} question={question} {...usersOfAnswer} />)); }; } Analysis.propTypes = propTypes; Analysis.defaultProps = defaultProps; function mapStateToProps(state) { const { lecture: { lecture: { id } }, analysis: { questions, questionIndex, question_answers, answers, loadingQuestions_ } } = state.flass.lecture; return { lectureId: id, questions, questionIndex, question_answers, answers, loadingQuestions_ }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ requestLectureAnalysisAction: (lectureId, questionIndex) => ({ type: REQUEST_LECTURE_ANALYSIS, lectureId, questionIndex }), unmountAnalysisAction: () => ({ type: UNMOUNT_ANALYSIS }) }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(AnalysisFetchHOC(AnalysisMapAnswersHOC(AnalysisLoadingHOC(Analysis))));
17-react-todos-redux-es7-decorator/src/app/components/todo-list.js
iproduct/course-node-express-react
import React from 'react'; import Todo from './todo'; import TodoDetails from './todo-details'; import { CSSTransitionGroup } from 'react-transition-group'; import AnimationOnPropsChange from './animation-on-props-change'; import { connect } from 'react-redux'; import { changeStatus, selectTodo, editTodo, deleteTodo} from '../actions'; const getVisibleTodos = (todos, filter) => { const filteredTodos = todos.filter(todo => filter === 'all' ? true : todo.status === filter); console.log(filteredTodos); return filteredTodos; }; const mapStateToProps = (state) => ({ todos: getVisibleTodos(state.todos, state.visibilityFilter), selectedTodo: state.selectedTodo }); const mapDispatchToProps = (dispatch) => ({ onTodoEdited: (todo) => { dispatch(editTodo(todo)); dispatch(selectTodo(null)); }, onTodoCanceled: () => { dispatch(selectTodo(null)); }, onTodoSelected: (todo) => { dispatch(selectTodo(todo)); }, onCompleted: (id) => { dispatch(changeStatus(id, 'completed')); }, onCanceled: (id) => { dispatch(changeStatus(id, 'canceled')); }, onDelete: (id) => { dispatch(deleteTodo(id)); } }); @connect( mapStateToProps, mapDispatchToProps ) export default class TodoList extends React.Component { constructor(props) { super(props); this.prevSelectedTodo = null; } componentWillReceiveProps(nextProps) { if (this.props.selectedTodo !== nextProps.selectedTodo) { this.prevSelectedTodo = this.props.selectedTodo; } } render() { let { selectedTodo, todos, ...rest } = this.props; return ( <div> <ul className="todo-list list-group"> <CSSTransitionGroup transitionName="todos" transitionEnterTimeout={1000} transitionLeaveTimeout={1000}> {todos.map(todo => ( <li key={todo.id} className="list-group-item"> <Todo todo={todo} {...rest} /> </li> )) } </CSSTransitionGroup> </ul> <AnimationOnPropsChange shouldFadeOut={this.prevSelectedTodo !== null} shouldFadeIn={selectedTodo !== null} todo={selectedTodo} {...rest}> <TodoDetails /> </AnimationOnPropsChange> </div> ); } }
gadget-system-teamwork/src/components/gadgets/EditGadgetPage.js
TeodorDimitrov89/JS-Web-Teamwork-2017
import React from 'react' import gadgetActions from '../../actions/GadgetActions' import gadgetStore from '../../stores/GadgetStore' import EditGadgetForm from './EditGadgetForm' import FormHelpers from '../common/forms/FormHelpers' import toastr from 'toastr' class EditGadgetPage extends React.Component { constructor (props) { super(props) this.state = { gadgetId: this.props.match.params.id, gadget: { title: '', description: '', image: '', price: 0, quantityOnStock: 0 }, error: '' } this.handleGadgetChange = this.handleGadgetChange.bind(this) this.handleEditFetching = this.handleEditFetching.bind(this) this.handleGadgetForm = this.handleGadgetForm.bind(this) this.handleGadgetEdit = this.handleGadgetEdit.bind(this) gadgetStore.on(gadgetStore.eventTypes.EDIT_GADGET_FETCHED, this.handleEditFetching) gadgetStore.on(gadgetStore.eventTypes.GADGET_EDITED, this.handleGadgetEdit) } componentDidMount () { gadgetActions.editGet(this.state.gadgetId) } componentWillUnmount () { gadgetStore.removeListener(gadgetStore.eventTypes.EDIT_GADGET_FETCHED, this.handleEditFetching) gadgetStore.removeListener(gadgetStore.eventTypes.GADGET_EDITED, this.handleGadgetEdit) } handleGadgetChange (event) { FormHelpers.handleFormChange.bind(this)(event, 'gadget') } handleEditFetching (editGadget) { this.setState({gadget: editGadget}) } handleGadgetForm (event) { event.preventDefault() gadgetActions.editPost(this.state.gadget) } handleGadgetEdit (data) { toastr.success(data.message) this.props.history.push('/') } render () { return ( <div> <h1>Edit Gadget</h1> <EditGadgetForm gadget={this.state.gadget} error={this.state.error} onChange={this.handleGadgetChange} onEdit={this.handleGadgetForm} /> </div> ) } } export default EditGadgetPage
src/components/RenderToBody.js
luanhaipeng/coolpeng-react
import React from 'react'; import ReactDOM from 'react-dom'; // 将子组件渲染到 document.body 上 export default class RenderToBody extends React.Component { static propTypes = { children: React.PropTypes.node.isRequired // 只允许传单个子组件 }; componentDidMount() { this._innerContainer = document.createElement('div'); document.body.appendChild(this._innerContainer); this._renderLayer(); } componentDidUpdate() { this._renderLayer(); } componentWillUnmount() { ReactDOM.unmountComponentAtNode(this._innerContainer); document.body.removeChild(this._innerContainer); this._innerContainer = null; } _renderLayer() { ReactDOM.render(React.Children.only(this.props.children), this._innerContainer); } render() { // Render a placeholder return <div></div>; } }
src/components/Connections/Toolbar.js
SteMcLellan/queryman
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { getConnectionStateFromProps } from './selectors.js'; import { actions } from './component.js'; import { actions as query_actions } from '../Query/component.js'; const T_mapStateToProps = (state, ownProps) => { return { cxn: getConnectionStateFromProps(state, ownProps) }; }; const T_mapDispatchToProps = (dispatch) => { return { addQuery: (cxnid) => { dispatch(query_actions.connectAndAddConnection({cxnid})); } } }; let Toolbar = ({ cxn, addQuery, connect }) => { return ( <div className='btn-group'> <button className='btn btn-default' title='New Query' onClick={() => addQuery(cxn.id)}> <span className='icon icon-doc-text-inv icon-text'></span> New Query </button> </div> ); }; Toolbar = connect(T_mapStateToProps, T_mapDispatchToProps)(Toolbar); export default Toolbar;
src/layouts/UserLayout.js
wu-sheng/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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, Redirect, Switch, Route } from 'dva/router'; import DocumentTitle from 'react-document-title'; import { Icon } from 'antd'; import GlobalFooter from '../components/GlobalFooter'; import styles from './UserLayout.less'; import logo from '../assets/sw-2.png'; import { getRoutes } from '../utils/utils'; const copyright = <div>Copyright <Icon type="copyright" /> 2017 - 2019 The Apache Software Foundation, Licensed under the Apache License, Version 2.0.</div>; class UserLayout extends React.PureComponent { getPageTitle() { const { routerData, location } = this.props; const { pathname } = location; let title = 'SkyWalking'; if (routerData[pathname] && routerData[pathname].name) { title = `${routerData[pathname].name} - SkyWalking`; } return title; } render() { const { routerData, match } = this.props; return ( <DocumentTitle title={this.getPageTitle()}> <div className={styles.container}> <div className={styles.content}> <div className={styles.top}> <div className={styles.header}> <Link to="/"> <img alt="logo" className={styles.logo} src={logo} /> <span className={styles.title}>Apache SkyWalking</span> </Link> </div> <div className={styles.desc}>Apache SkyWalking APM System</div> </div> <Switch> {getRoutes(match.path, routerData).map(item => ( <Route key={item.key} path={item.path} component={item.component} exact={item.exact} /> ) )} <Redirect exact from="/user" to="/user/login" /> </Switch> </div> <GlobalFooter copyright={copyright} /> </div> </DocumentTitle> ); } } export default UserLayout;
client/src/Application/Application.js
Fasand/youtube-monitor
import React from 'react'; class Application extends React.Component { render () { return <h1>Application</h1>; } } export default Application;
stories/pageheader.stories.js
JimBarrows/Bootstrap-React-Components
import {storiesOf} from '@storybook/react' import React from 'react' import PageHeader from '../src/PageHeader' storiesOf('Page Header', module) .addDecorator((story) => <div className="container"> {story()} </div>) .add('Basic', () => <PageHeader id={'basic'}><h1>Page Header</h1></PageHeader>) .add('With muted', () => <PageHeader id={'basic-muted'}><h3>Page Header</h3><small className="text-muted">Small muted text</small></PageHeader>)
src/components/Footer/Footer.js
agiron123/react-starter-kit-TDDOList
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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 './Footer.css'; import Link from '../Link'; function Footer() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Your Company</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/">Home</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/privacy">Privacy</Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/not-found">Not Found</Link> </div> </div> ); } export default withStyles(s)(Footer);
indico/modules/rb/client/js/common/map/util.js
pferreir/indico
// This file is part of Indico. // Copyright (C) 2002 - 2021 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 LatLon from 'geodesy/latlon-nvector-spherical'; import _ from 'lodash'; import PropTypes from 'prop-types'; import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as mapActions from './actions'; import * as mapSelectors from './selectors'; export function getAreaBounds(area) { return { SW: [area.top_left_latitude, area.top_left_longitude], NE: [area.bottom_right_latitude, area.bottom_right_longitude], }; } export function getMapBounds(map) { const boundsObj = map.getBounds(); return { SW: Object.values(boundsObj.getSouthWest()), NE: Object.values(boundsObj.getNorthEast()), }; } /** Calculate a bounding box that encompasses all the rooms provided in an array. */ export function checkRoomsInBounds(rooms, bounds) { if (!rooms.length) { return null; } const polygon = [ new LatLon(bounds.NE[0], bounds.NE[1]), new LatLon(bounds.NE[0], bounds.SW[1]), new LatLon(bounds.SW[0], bounds.SW[1]), new LatLon(bounds.SW[0], bounds.NE[1]), ]; return rooms.every(({lat, lng}) => new LatLon(lat, lng).isEnclosedBy(polygon)); } export function getRoomListBounds(rooms) { if (!rooms.length) { return null; } const points = rooms.map(({lat, lng}) => new LatLon(lat, lng)); const center = LatLon.meanOf(points); const farthest = _.max(points.map(p => center.distanceTo(p))) * 1.1; const sw = center.destinationPoint(farthest, 225); const ne = center.destinationPoint(farthest, 45); return { SW: [sw.lat, sw.lon], NE: [ne.lat, ne.lon], }; } /** Return something like xx°yy′zz″N, ... */ export function formatLatLon(lat, lon) { return new LatLon(lat, lon).toString('dms', 2); } /** This is a HOC that adds mouse hover behaviour to Rooms */ export function withHoverListener(RoomComponent) { const refCache = {}; class RoomHoverWrapper extends React.Component { static propTypes = { hoveredRoomId: PropTypes.number, actions: PropTypes.object.isRequired, room: PropTypes.object.isRequired, inSelectionMode: PropTypes.bool, selectedRooms: PropTypes.object, }; static defaultProps = { hoveredRoomId: null, inSelectionMode: false, selectedRooms: {}, }; shouldComponentUpdate({hoveredRoomId: newId, actions, room, ...restProps}) { const {hoveredRoomId: currentId, room: oldRoom, actions: __, ...oldRestProps} = this.props; // IMPORTANT: we only want this update to occurr when really needed // - whenever this room is going from hovered -> non-hovered // - whenever this room is going from non-hovered -> hovered // - whenever any of the other props change (selection) // - whenever room props change (user booking permissions) return ( newId === room.id || currentId === room.id || !_.isEqual(room, oldRoom) || !_.isEqual(restProps, oldRestProps) ); } render() { const {hoveredRoomId, actions, room} = this.props; if (!refCache[room.id]) { refCache[room.id] = React.createRef(); } return React.createElement(RoomComponent, { room, onMouseEnter: () => { if (room.id !== hoveredRoomId) { actions.setRoomHover(room.id); } }, onMouseLeave: () => { if (hoveredRoomId !== null) { actions.setRoomHover(null); } }, }); } } return connect( state => ({ hoveredRoomId: mapSelectors.getHoveredRoom(state), }), dispatch => ({ actions: bindActionCreators( { setRoomHover: mapActions.setRoomHover, }, dispatch ), }) )(RoomHoverWrapper); }
src/renderer/components/root.js
ka2n/retro-twitter-client
import { connect } from 'react-redux' import AccountSwitcher from './account-switcher' import ContextSwitcher from './channel-switcher' import ipc from 'ipc' import Main from './main' import React from 'react'; import { fetchAccount, fetchTweets, fetchLists, openUrl, postTweet, searchTweets, selectChannel, selectNextChannel, selectPreviousChannel, subscribeStream } from '../libraries/action-creators' class Root extends React.Component { componentDidMount() { this.props.dispatch(fetchAccount()); ipc.on('select-next-channel-requested', () => { this.props.dispatch(selectNextChannel()); }); ipc.on('select-previous-channel-requested', () => { this.props.dispatch(selectPreviousChannel()); }); } onAnchorClicked(url) { this.props.dispatch(openUrl(url)); } onChannelClicked(channelId) { this.props.dispatch(selectChannel(channelId)); } postTweet(text) { this.props.dispatch(postTweet(text)); } render() { return( <div className="root"> <AccountSwitcher account={this.props.account} /> <ContextSwitcher account={this.props.account} channelId={this.props.channelId} lists={this.props.lists} onChannelClicked={this.onChannelClicked.bind(this)} /> <Main channelId={this.props.channelId} onAnchorClicked={this.onAnchorClicked.bind(this)} postTweet={this.postTweet.bind(this)} homeTimeline={this.props.homeTimeline} listTweets={this.props.listTweets} searchedTweets={this.props.searchedTweets} /> </div> ); } } function mapStateToProps(state) { return state; } export default connect(mapStateToProps)(Root);
app/javascript/mastodon/features/favourites/index.js
honpya/taketodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavourites } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll-4'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]), }); @connect(mapStateToProps) export default class Favourites extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchFavourites(this.props.params.statusId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(nextProps.params.statusId)); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='favourites'> <div className='scrollable'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } }
src/components/ui/ListItem.js
eventures-io/ldn-retail-demo
/** * List Items * <ListItem title={'Hello World'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ListItem } from 'react-native-elements'; // Consts and Libs import { AppColors, AppStyles } from '@theme/'; /* Component ==================================================================== */ class CustomListItem extends Component { static propTypes = { containerStyle: PropTypes.oneOfType([ PropTypes.array, PropTypes.shape({}), ]), titleStyle: PropTypes.oneOfType([ PropTypes.array, PropTypes.shape({}), ]), subtitleStyle: PropTypes.oneOfType([ PropTypes.array, PropTypes.shape({}), ]), } static defaultProps = { containerStyle: [], titleStyle: [], subtitleStyle: [], } listItemProps = () => { // Defaults const props = { title: 'Coming Soon...', chevronColor: AppColors.textSecondary, underlayColor: AppColors.border, ...this.props, containerStyle: [{ backgroundColor: AppColors.listItemBackground, borderTopColor: AppColors.border, borderBottomColor: AppColors.border, }], titleStyle: [AppStyles.baseText], subtitleStyle: [AppStyles.subtext], }; if (this.props.containerStyle) { props.containerStyle.push(this.props.containerStyle); } if (this.props.titleStyle) { props.titleStyle.push(this.props.titleStyle); } if (this.props.subtitleStyle) { props.subtitleStyle.push(this.props.subtitleStyle); } return props; } render = () => <ListItem {...this.listItemProps()} />; } /* Export Component ==================================================================== */ export default CustomListItem;
src/app/Topics.js
cityofasheville/simplicity2
import React from 'react'; import PropTypes from 'prop-types'; import TopicCard from '../shared/TopicCard'; import { withLanguage } from '../utilities/lang/LanguageContext'; import { IM_TREE } from '../shared/iconConstants'; import Icon from '../shared/Icon'; const Topics = props => ( <div className="card-container"> <div className="row"> <div className="col-sm-12"> <h2>View citywide topic <strong>dashboards</strong> about your community.</h2> </div> </div> <div className="row topic-options"> {props.topics.map((topic, i) => ( <div className="card-item" key={['topic', i].join('_')}> <TopicCard topic={topic.name} lang={props.language.language} view={null} path={topic.path || topic.name} /> </div> ))} <div className="card-item"> <a className="topic-card" target='blank' href={'https://avl.maps.arcgis.com/apps/instant/lookup/index.html?appid=10e2c4ae45614b92ad4efaa61342b249%2F'}> <div className="topicCard"> <div className="text-primary text-center"><Icon path={IM_TREE} size={75} /></div> <div className="text-primary text-center"> CLIMATE JUSTICE </div> </div> </a> </div> </div> </div> ); // Topics.propTypes = { // topics: PropTypes.arrayOf([PropTypes.oneOf(PropTypes.string, PropTypes.shape({}))]), // }; Topics.defaultProps = { topics: [ // { // name: 'BUDGET', // path: 'budget', // }, { name: 'CAPITAL_PROJECTS', path: 'capital_projects', }, { name: 'DEVELOPMENT', path: '/development/major' }, ], }; export default withLanguage(Topics);
app/shared/modals/payment-terms/PaymentTermsModal.js
fastmonkeys/respa-ui
import React from 'react'; import PropTypes from 'prop-types'; import Modal from 'react-bootstrap/lib/Modal'; import injectT from '../../../i18n/injectT'; function PaymentTermsModal({ isOpen, onDismiss, t, }) { return ( <Modal className="app-PaymentTermsModal" onHide={onDismiss} show={isOpen} > <Modal.Header> <Modal.Title> {t('paymentTerms.title')} </Modal.Title> </Modal.Header> <Modal.Body> {t('paymentTerms.terms')} </Modal.Body> </Modal> ); } PaymentTermsModal.propTypes = { isOpen: PropTypes.bool.isRequired, onDismiss: PropTypes.func.isRequired, t: PropTypes.func.isRequired, }; export default injectT(PaymentTermsModal);
day17_todolist/src/components/App.js
eyesofkids/ironman2017
import React from 'react' import TodoList from './TodoList' class App extends React.Component { render() { return <TodoList initText="開始輸入文字吧!" /> } } // 輸出App模組 export default App
src/containers/DevTools.js
kun391/react-firebase-chat
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor defaultIsVisible={false} toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> );