path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/JSONValueNode.js
alexkuz/react-json-tree
import React from 'react'; import PropTypes from 'prop-types'; /** * Renders simple values (eg. strings, numbers, booleans, etc) */ const JSONValueNode = ({ nodeType, styling, labelRenderer, keyPath, valueRenderer, value, valueGetter }) => ( <li {...styling('value', nodeType, keyPath)}> <label {...styling(['label', 'valueLabel'], nodeType, keyPath)}> {labelRenderer(keyPath, nodeType, false, false)} </label> <span {...styling('valueText', nodeType, keyPath)}> {valueRenderer(valueGetter(value), value, ...keyPath)} </span> </li> ); JSONValueNode.propTypes = { nodeType: PropTypes.string.isRequired, styling: PropTypes.func.isRequired, labelRenderer: PropTypes.func.isRequired, keyPath: PropTypes.arrayOf( PropTypes.oneOfType([PropTypes.string, PropTypes.number]) ).isRequired, valueRenderer: PropTypes.func.isRequired, value: PropTypes.any, valueGetter: PropTypes.func }; JSONValueNode.defaultProps = { valueGetter: value => value }; export default JSONValueNode;
src/svg-icons/action/dashboard.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDashboard = (props) => ( <SvgIcon {...props}> <path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/> </SvgIcon> ); ActionDashboard = pure(ActionDashboard); ActionDashboard.displayName = 'ActionDashboard'; ActionDashboard.muiName = 'SvgIcon'; export default ActionDashboard;
node_modules/_antd@2.13.4@antd/es/radio/group.js
ligangwolai/blog
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import shallowEqual from 'shallowequal'; import Radio from './radio'; function getCheckedValue(children) { var value = null; var matched = false; React.Children.forEach(children, function (radio) { if (radio && radio.props && radio.props.checked) { value = radio.props.value; matched = true; } }); return matched ? { value: value } : undefined; } var RadioGroup = function (_React$Component) { _inherits(RadioGroup, _React$Component); function RadioGroup(props) { _classCallCheck(this, RadioGroup); var _this = _possibleConstructorReturn(this, (RadioGroup.__proto__ || Object.getPrototypeOf(RadioGroup)).call(this, props)); _this.onRadioChange = function (ev) { var lastValue = _this.state.value; var value = ev.target.value; if (!('value' in _this.props)) { _this.setState({ value: value }); } var onChange = _this.props.onChange; if (onChange && value !== lastValue) { onChange(ev); } }; var value = void 0; if ('value' in props) { value = props.value; } else if ('defaultValue' in props) { value = props.defaultValue; } else { var checkedValue = getCheckedValue(props.children); value = checkedValue && checkedValue.value; } _this.state = { value: value }; return _this; } _createClass(RadioGroup, [{ key: 'getChildContext', value: function getChildContext() { return { radioGroup: { onChange: this.onRadioChange, value: this.state.value, disabled: this.props.disabled, name: this.props.name } }; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if ('value' in nextProps) { this.setState({ value: nextProps.value }); } else { var checkedValue = getCheckedValue(nextProps.children); if (checkedValue) { this.setState({ value: checkedValue.value }); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }, { key: 'render', value: function render() { var _this2 = this; var props = this.props; var _props$prefixCls = props.prefixCls, prefixCls = _props$prefixCls === undefined ? 'ant-radio-group' : _props$prefixCls, _props$className = props.className, className = _props$className === undefined ? '' : _props$className; var classString = classNames(prefixCls, _defineProperty({}, prefixCls + '-' + props.size, props.size), className); var children = props.children; // 如果存在 options, 优先使用 if (props.options && props.options.length > 0) { children = props.options.map(function (option, index) { if (typeof option === 'string') { return React.createElement( Radio, { key: index, disabled: _this2.props.disabled, value: option, onChange: _this2.onRadioChange, checked: _this2.state.value === option }, option ); } else { return React.createElement( Radio, { key: index, disabled: option.disabled || _this2.props.disabled, value: option.value, onChange: _this2.onRadioChange, checked: _this2.state.value === option.value }, option.label ); } }); } return React.createElement( 'div', { className: classString, style: props.style, onMouseEnter: props.onMouseEnter, onMouseLeave: props.onMouseLeave }, children ); } }]); return RadioGroup; }(React.Component); export default RadioGroup; RadioGroup.defaultProps = { disabled: false }; RadioGroup.childContextTypes = { radioGroup: PropTypes.any };
frontend/app_v2/src/components/DashboardHome/DashboardHomePresentation.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // FPCC import DashboardTiles from 'components/DashboardTiles' import { getMediaUrl } from 'common/urlHelpers' function DashboardHomePresentation({ site, tiles, currentUser }) { return ( <main id="DashboardHome"> <div className="max-w-3xl mx-auto p-4 sm:p-6 lg:max-w-7xl lg:p-8"> <h1 className="sr-only">Profile</h1> <div className="grid grid-cols-1 gap-4 items-start lg:grid-cols-3 lg:gap-8"> <div className="grid grid-cols-1 gap-4 lg:col-span-2"> {/* Welcome panel */} <section id="UserDashboardHeader"> <div className="rounded-lg bg-white overflow-hidden shadow"> <h2 className="sr-only" id="profile-overview-title"> Profile Overview </h2> <div className="bg-white p-6"> <div className="sm:flex sm:items-center sm:justify-between"> <div className="flex space-x-5"> <div className="flex-shrink-0"> <div className="flex max-w-xs p-3 bg-secondary hover:bg-secondary-dark text-white text-3xl rounded-full h-20 w-20 items-center justify-center"> {currentUser?.userInitials} </div> </div> <div className="pt-1 text-left"> <p className="text-sm font-medium text-fv-charcoal-light">Welcome back,</p> <p className="font-bold text-fv-charcoal text-2xl">{currentUser.displayName}</p> <p className="text-sm font-medium text-fv-charcoal-light">{currentUser.role}</p> </div> </div> <div className="flex items-center space-x-5"> <div className="pt-1 text-right"> <p className="text-xl font-bold text-fv-charcoal">You are on:</p> <p className="text-xl font-medium text-fv-charcoal-light">{site?.title}</p> </div> <div className="flex-shrink-0"> {site?.logoId ? ( <img className="flex max-w-xs bg-gray-300 rounded-full h-20 w-20 items-center justify-center" src={getMediaUrl({ type: 'image', id: site?.logoId, viewName: 'Thumbnail', })} alt="Site Logo" /> ) : ( <div className="flex max-w-xs p-3 bg-secondary hover:bg-secondary-dark text-white text-3xl rounded-full h-20 w-20 items-center justify-center"> <span className="text-center">{site?.title?.charAt(0)}</span> </div> )} </div> </div> </div> </div> </div> </section> <DashboardTiles.Presentation tileContent={tiles} /> </div> </div> </div> </main> ) } // PROPTYPES const { array, object } = PropTypes DashboardHomePresentation.propTypes = { currentUser: object, site: object, tiles: array, } export default DashboardHomePresentation
packages/react-server-website/pages/source.js
lidawang/react-server
import React from 'react'; import {ReactServerAgent, RootContainer} from 'react-server'; import SourceBody from '../components/source-body'; import PageTitle from '../components/page-title'; import SourceContents from '../components/source-contents'; import DataBundleCacheManager from '../middleware/DataBundleCache'; import './source.less'; export default class SourcePage { handleRoute(next) { const page = this.getRequest().getRouteParams().path; this.bodyPromise = page && ReactServerAgent.get('/api/source', {page}) .then(({body}) => body) this.contentsPromise = ReactServerAgent.get('/api/source-contents') .then(({body}) => body) .then(SourceContents.setResponse) .then(DataBundleCacheManager.addContents.bind({}, '/source/')) return next(); } getTitle() { return this.contentsPromise .then(() => `Source of ${SourceContents.activePageName()}`); } getElements() { return ( <RootContainer className='SourcePage'> <RootContainer when={this.contentsPromise}> <SourceContents /> <PageTitle titleProvider={SourceContents} /> </RootContainer> <RootContainer className='rootContent' when={this.bodyPromise}> <SourceBody /> </RootContainer> </RootContainer> ); } }
test/unit/shared/routes-test.js
travi-org/admin.travi.org
import React from 'react'; import dom from 'react-dom'; import {Router, createMemoryHistory} from 'react-router'; import proxyquire from 'proxyquire'; import {assert} from 'chai'; suite('routes', () => { const routes = proxyquire('../../../src/shared/routes', { './views/theme/wrap/component': { default: ({children}) => ( <div> wrapper {' '} {children} </div> ) }, '@travi/admin.travi.org-components': { Index: () => <div>index</div>, NotFound: () => <div>not-found</div> }, './views/resources/list/connected-list': { default: () => <div>resources</div> }, './views/resources/individual/connected-resource': { default: () => <div>resource</div> }, './views/persons/individual/component': { default: () => <div>person</div> } }) .getRoutes(); let node; setup(() => { node = global.document.createElement('div'); }); teardown(() => dom.unmountComponentAtNode(node)); test('that the root route is defined', () => { dom.render( <Router history={createMemoryHistory('/')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper index') ); }); test('that the not-found route is defined', () => { dom.render( <Router history={createMemoryHistory('/foo/bar/baz')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper not-found') ); }); test('that the rides route is defined', () => { dom.render( <Router history={createMemoryHistory('/rides')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper resources') ); }); test('that the ride route is defined', () => { dom.render( <Router history={createMemoryHistory('/rides/8')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper resource') ); }); test('that the users route is defined', () => { dom.render( <Router history={createMemoryHistory('/users')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper resources') ); }); test('that the user route is defined', () => { dom.render( <Router history={createMemoryHistory('/persons/4')}>{routes}</Router>, node, () => assert.equal(node.textContent, 'wrapper person') ); }); });
FirstRedux/src/components/TodoList/TodoList.js
Louis0503/TestRact
import React from 'react'; const TodoList = ({ todos, onDeleteTodo, }) => ( <div> <ul> { todos.map((todo, index) => ( <li key={index}> {todo.get('text')} <button onClick={onDeleteTodo(index)}>Delete</button> </li> )).toJS() } </ul> </div> ); export default TodoList;
src/containers/menuSections/numericIncrementorMenu.js
Harlantr/text-mod
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { changeText } from '../../actions/actions'; import incrementors from '../../const/incrementors'; class NumericIncrementorMenu extends Component { constructor (props) { super(props); this.addNumericVariable = this.addNumericVariable.bind(this); } addNumericVariable () { const newString = this.props.userText + incrementors.number; this.props.changeText(newString); } render () { return ( <div> <h5> <button className="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored menu-btn" onClick={this.addNumericVariable} title="Inject"> <i className="material-icons">add</i> </button> Numeric incrementor (~n) </h5> </div> ); } } const mapStateToProps = state => ({ userText: state.reducer.userText, numericIncrementorOptions: state.reducer.numericIncrementorOptions }) const mapDispatchToProps = dispatch => bindActionCreators({ changeText }, dispatch) export default connect( mapStateToProps, mapDispatchToProps )(NumericIncrementorMenu)
front/src/components/auth-redirect/auth-redirect.js
kris71990/travelapp
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; function AuthRedirect(props) { const { token, location } = props; let redirectRoute; if (location.pathname === '/login' || location.pathname === '/signup' || location.pathname === '/') { if (token) { redirectRoute = '/me'; } } else if (!token) { redirectRoute = '/signup'; } return ( <div> { redirectRoute ? <Redirect to={ redirectRoute }/> : undefined } </div> ); } AuthRedirect.propTypes = { token: PropTypes.string, location: PropTypes.object, }; const mapStateToProps = state => ({ token: state.auth, }); export default connect(mapStateToProps)(AuthRedirect);
docs/public/static/examples/unversioned/tutorial/sharing-web-workaround.js
exponentjs/exponent
import React from 'react'; import { Image, Platform, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import * as ImagePicker from 'expo-image-picker'; import * as Sharing from 'expo-sharing'; import uploadToAnonymousFilesAsync from 'anonymous-files'; export default function App() { let [selectedImage, setSelectedImage] = React.useState(null); let openImagePickerAsync = async () => { let permissionResult = await ImagePicker.requestCameraRollPermissionsAsync(); if (permissionResult.granted === false) { alert('Permission to access camera roll is required!'); return; } let pickerResult = await ImagePicker.launchImageLibraryAsync(); if (pickerResult.cancelled === true) { return; } if (Platform.OS === 'web') { let remoteUri = await uploadToAnonymousFilesAsync(pickerResult.uri); setSelectedImage({ localUri: pickerResult.uri, remoteUri }); } else { setSelectedImage({ localUri: pickerResult.uri, remoteUri: null }); } }; let openShareDialogAsync = async () => { if (!(await Sharing.isAvailableAsync())) { alert(`The image is available for sharing at: ${selectedImage.remoteUri}`); return; } Sharing.shareAsync(selectedImage.remoteUri || selectedImage.localUri); }; if (selectedImage !== null) { return ( <View style={styles.container}> <Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} /> <TouchableOpacity onPress={openShareDialogAsync} style={styles.button}> <Text style={styles.buttonText}>Share this photo</Text> </TouchableOpacity> </View> ); } return ( <View style={styles.container}> <Image source={{ uri: 'https://i.imgur.com/TkIrScD.png' }} style={styles.logo} /> <Text style={styles.instructions}> To share a photo from your phone with a friend, just press the button below! </Text> <TouchableOpacity onPress={openImagePickerAsync} style={styles.button}> <Text style={styles.buttonText}>Pick a photo</Text> </TouchableOpacity> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, logo: { width: 305, height: 159, marginBottom: 20, }, instructions: { color: '#888', fontSize: 18, marginHorizontal: 15, marginBottom: 10, }, button: { backgroundColor: 'blue', padding: 20, borderRadius: 5, }, buttonText: { fontSize: 20, color: '#fff', }, thumbnail: { width: 300, height: 300, resizeMode: 'contain', }, });
examples/react/app/index.js
tcurdt/xstatic
import React from 'react' import { render } from 'react-dom' import configureStore from './store/configureStore' import Root from './containers/Root' const store = configureStore() render( <Root store={store} />, document.getElementById('root'))
frontend/app/components/Loadable.js
briancappello/flask-react-spa
import React from 'react' import Loadable from 'react-loadable' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { showLoading, hideLoading } from 'react-redux-loading-bar' /** * Provide an integration between react-loadable and react-redux-loading-bar * * The ProgressBar component is already rendered by components/App.js, * and it listens for the actions we're dispatching from this component's * lifecycle events */ class LoadableProgressComponent extends React.Component { componentWillMount() { this.props.showLoading() } componentWillUnmount() { this.props.hideLoading() } render() { return null } } export default ({ loader }) => Loadable({ loader, delay: 0, // react-redux-loading-bar has its own time delay handling loading: connect( (state) => ({}), (dispatch) => bindActionCreators({ showLoading, hideLoading }, dispatch), )(LoadableProgressComponent), })
packages/veritone-react-common/src/components/Lozenge/index.js
veritone/veritone-sdk
import React from 'react'; import { string, node } from 'prop-types'; import indigo from '@material-ui/core/colors/indigo'; import { makeStyles } from '@material-ui/styles'; import styles from './styles'; const useStyles = makeStyles(styles); const Lozenge = ({ children, iconClassName, backgroundColor, textColor, border, className, ...props }) => { const classes = useStyles(); return ( <div className={className || classes.lozenge} style={{ backgroundColor: backgroundColor || indigo[500], color: textColor || '#fff', border: border || 'none' }} {...props} > {iconClassName && <i className={iconClassName} />} {children} </div> ); }; Lozenge.propTypes = { children: node.isRequired, iconClassName: string, backgroundColor: string, textColor: string, border: string, className: string }; export default Lozenge;
src/svg-icons/content/remove-circle-outline.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentRemoveCircleOutline = (props) => ( <SvgIcon {...props}> <path d="M7 11v2h10v-2H7zm5-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ContentRemoveCircleOutline = pure(ContentRemoveCircleOutline); ContentRemoveCircleOutline.displayName = 'ContentRemoveCircleOutline'; ContentRemoveCircleOutline.muiName = 'SvgIcon'; export default ContentRemoveCircleOutline;
app/index.js
Thecontrarian/bmux
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.css'; const store = configureStore(); render( <Provider store={store}> <Router> {routes} </Router> </Provider>, document.getElementById('root') ); if (process.env.NODE_ENV !== 'production') { // Use require because imports can't be conditional. // In production, you should ensure process.env.NODE_ENV // is envified so that Uglify can eliminate this // module and its dependencies as dead code. // require('./createDevToolsWindow')(store); }
src/index.js
mikeastock/LonelyKnight
import React from 'react'; import Board from './Board'; import { observe } from './Game'; const rootEl = document.getElementById('root'); observe(knightPosition => React.render( <Board knightPosition={knightPosition}/>, rootEl ) );
resources/react/components/parts/schedule/ScheduleContentHeadingIcon.js
fetus-hina/stat.ink
import PropTypes from 'prop-types'; import React from 'react'; export default function ScheduleContentHeadingIcon (props) { const { schedule } = props; if (!schedule || !schedule.rule || !schedule.rule.icon) { return null; } return ( <img src={schedule.rule.icon} className='mr-1' /> ); } ScheduleContentHeadingIcon.propTypes = { schedule: PropTypes.object };
app/index.js
willy-claes/django-react
import React from 'react' import ReactDOM from 'react-dom' import createStore from 'App/store' import createRoutes from 'App/routes' import AppContainer from 'App/containers/AppContainer' const initialState = typeof window.__INITIAL_STATE__ === 'string' ? JSON.parse(window.__INITIAL_STATE__) : window.__INITIAL_STATE__ const store = createStore(initialState) const routes = createRoutes(store) const MOUNT_NODE = document.getElementById('root') const render = () => { ReactDOM.render( <AppContainer store={store} routes={routes} />, MOUNT_NODE // eslint-disable-line comma-dangle ) } render()
src/components/video_list.js
mrjkc/react-redux
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return <VideoListItem key={video.etag} video={video} /> }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
app/javascript/mastodon/containers/mastodon.js
tootcafe/mastodon
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { BrowserRouter, Route } from 'react-router-dom'; import { ScrollContext } from 'react-router-scroll-4'; import UI from '../features/ui'; import { fetchCustomEmojis } from '../actions/custom_emojis'; import { hydrateStore } from '../actions/store'; import { connectUserStream } from '../actions/streaming'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; import initialState from '../initial_state'; import ErrorBoundary from '../components/error_boundary'; const { localeData, messages } = getLocale(); addLocaleData(localeData); export const store = configureStore(); const hydrateAction = hydrateStore(initialState); store.dispatch(hydrateAction); store.dispatch(fetchCustomEmojis()); export default class Mastodon extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; componentDidMount() { this.disconnect = store.dispatch(connectUserStream()); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } shouldUpdateScroll (prevRouterProps, { location }) { return !(location.state?.mastodonModalKey && location.state?.mastodonModalKey !== prevRouterProps?.location?.state?.mastodonModalKey); } render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <ErrorBoundary> <BrowserRouter basename='/web'> <ScrollContext shouldUpdateScroll={this.shouldUpdateScroll}> <Route path='/' component={UI} /> </ScrollContext> </BrowserRouter> </ErrorBoundary> </Provider> </IntlProvider> ); } }
src/svg-icons/content/next-week.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentNextWeek = (props) => ( <SvgIcon {...props}> <path d="M20 7h-4V5c0-.55-.22-1.05-.59-1.41C15.05 3.22 14.55 3 14 3h-4c-1.1 0-2 .9-2 2v2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM10 5h4v2h-4V5zm1 13.5l-1-1 3-3-3-3 1-1 4 4-4 4z"/> </SvgIcon> ); ContentNextWeek = pure(ContentNextWeek); ContentNextWeek.displayName = 'ContentNextWeek'; ContentNextWeek.muiName = 'SvgIcon'; export default ContentNextWeek;
client/containers/HomePage/__tests__/App.spec.js
Vandivier/document-hello-world-docker-test
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { shallow, mount } from 'enzyme'; import { App } from '../App'; import styles from '../App.css'; import { intlShape } from 'react-intl'; import { intl } from '../../../util/react-intl-test-helper'; import { toggleAddPost } from '../AppActions'; const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] }; const children = <h1>Test</h1>; const dispatch = sinon.spy(); const props = { children, dispatch, intl: intlProp, }; test('renders properly', t => { const wrapper = shallow( <App {...props} /> ); // t.is(wrapper.find('Helmet').length, 1); t.is(wrapper.find('Header').length, 1); t.is(wrapper.find('Footer').length, 1); t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection); t.truthy(wrapper.find('Header + div').hasClass(styles.container)); t.truthy(wrapper.find('Header + div').children(), children); }); test('calls componentDidMount', t => { sinon.spy(App.prototype, 'componentDidMount'); mount( <App {...props} />, { context: { router: { isActive: sinon.stub().returns(true), push: sinon.stub(), replace: sinon.stub(), go: sinon.stub(), goBack: sinon.stub(), goForward: sinon.stub(), setRouteLeaveHook: sinon.stub(), createHref: sinon.stub(), }, intl, }, childContextTypes: { router: React.PropTypes.object, intl: intlShape, }, }, ); t.truthy(App.prototype.componentDidMount.calledOnce); App.prototype.componentDidMount.restore(); }); test('calling toggleAddPostSection dispatches toggleAddPost', t => { const wrapper = shallow( <App {...props} /> ); wrapper.instance().toggleAddPostSection(); t.truthy(dispatch.calledOnce); t.truthy(dispatch.calledWith(toggleAddPost())); });
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
scyankai/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-and-default"> {this.state.users.map(user => <div key={user.id}> {user.name} </div> )} </div> ); } }
src/svg-icons/image/healing.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageHealing = (props) => ( <SvgIcon {...props}> <path d="M17.73 12.02l3.98-3.98c.39-.39.39-1.02 0-1.41l-4.34-4.34c-.39-.39-1.02-.39-1.41 0l-3.98 3.98L8 2.29C7.8 2.1 7.55 2 7.29 2c-.25 0-.51.1-.7.29L2.25 6.63c-.39.39-.39 1.02 0 1.41l3.98 3.98L2.25 16c-.39.39-.39 1.02 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34c.39-.39.39-1.02 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z"/> </SvgIcon> ); ImageHealing = pure(ImageHealing); ImageHealing.displayName = 'ImageHealing'; ImageHealing.muiName = 'SvgIcon'; export default ImageHealing;
examples/official-storybook/stories/addon-measure/StackingLabels.stories.js
storybooks/storybook
import React from 'react'; import { Visualization } from '../../components/addon-measure/Visualization'; export default { title: 'Addons/Measure/StackingLabels', parameters: { layout: 'fullscreen', }, }; const Template = (args) => <Visualization {...args} />; export const EverythingUniform = Template.bind({}); EverythingUniform.args = { render: (ref) => ( <div ref={ref} style={{ outline: '1px solid black', width: 256, height: 256, border: '8px solid transparent', padding: 16, margin: 32, }} /> ), }; export const Asymmetric = Template.bind({}); Asymmetric.args = { render: (ref) => ( <div ref={ref} style={{ outline: '1px solid black', width: 256, height: 256, margin: '8px 16px 32px 64px', padding: '64px 32px 16px 8px', borderTop: '8px solid transparent', borderRight: '16px solid transparent', borderBottom: '32px solid transparent', borderLeft: '12px solid transparent', }} /> ), }; export const MoreAsymmetric = Template.bind({}); MoreAsymmetric.args = { render: (ref) => ( <div ref={ref} style={{ outline: '1px solid black', width: 256, height: 256, margin: '0 0 32px 64px', padding: '64px 32px 16px 0', borderTop: '8px solid transparent', borderRight: '16px solid transparent', borderLeft: '12px solid transparent', }} /> ), };
src/components/Projects.js
jlekas/Site
import React from 'react'; import Youtube from 'react-youtube'; export default class Projects extends React.Component { constructor(props) { super(props); this.state = { projects: [ { title:"Ramp", descript:[ "Developed a peer to peer application in python that allows users to chat, share and send files, as well as video chat with one another through a TCP connection", "Implemented a SQLite database to store, maintain, and update messages and files on each peer's local computer" ], date: "Feb-May 2017" }, { title: "Term Project", descript:[ "Created a application where users were able to find buildings and food locations around the CMU campus", "Developed a breadth first searching algorithm to find the shortest path between locations", "Implemented web scraping techniques to find which locations around campus were open at the time the user accessed the program" ], date: "Nov-Dec 2015" }, { title: "Proxy Server", descript:[ "Created a proxy server in C that would handle GET requests in both HTTP/1.0 and HTTP/1.1 and forward the responses to a specified client" ], date: "Nov 2016" }, { title: "C0 Virtual Machine", descript: [ "I created a virtual machine that was able to execute C0 code (a safer version of C that is taught at Carnegie Mellon), and take care of memory and data manipulations" ], date: "Apr 2016" }, { title: "Personal Website", descript:[ "Developed a personal website using React.js and ES6 that displays my interest in web development and showcases techniques such as a parallaxing background" ], date: "Dec 2016" } ] }; }; render() { const opts = { height: '500', width: '600', playerVars: { autoplay: 1 } }; var Proj = []; Proj.push(<Youtube videoId="w4GK9CzhG8E" opts={opts} onReady={this._onReady} />); Proj.push(<Youtube videoId="lIAgVkB7Yc4" opts={opts} onReady={this._onReady} />); this.state.projects.forEach(function(p) { Proj.push(<Individual p={p} />) }); return( <div className="projectContainer" id="Projects"> <h2>Projects</h2> <table> <tbody className="Individual"> {Proj} </tbody> </table> </div> ); } _onReady(event) { event.target.pauseVideo(); } } class Individual extends React.Component { constructor(props) { super(props); }; render() { var Descript = []; this.props.p.descript.forEach(function(d) { Descript.push(<li>{d}</li>); }); return( <div> <tr> <td className="title" colSpan={3}>{this.props.p.title}</td> </tr> <tr> <td colSpan={1} className="Dates">{this.props.p.date}</td> <td colSpan={2} className="description"><ul>{Descript}</ul></td> </tr> </div> ); } }
web/src/components/blog-post-preview-list.js
ajmalafif/ajmalafif.com
import {Link} from 'gatsby' import React from 'react' import BlogPostPreview from './blog-post-preview' function BlogPostPreviewGrid (props) { return ( <div> {props.title && <h2>{props.title}</h2>} <ul> {props.nodes && props.nodes.map(node => ( <li key={node.id} style={{ listStyleType: 'none' }}> <BlogPostPreview {...node} isInList /> </li> ))} </ul> </div> ) } BlogPostPreviewGrid.defaultProps = { title: '', nodes: [], browseMoreHref: '' } export default BlogPostPreviewGrid
react-router-tutorial/lessons/14-whats-next/modules/routes.js
zerotung/practices-and-notes
import React from 'react' import { Route, IndexRoute } from 'react-router' import App from './App' import About from './About' import Repos from './Repos' import Repo from './Repo' import Home from './Home' module.exports = ( <Route path="/" component={App}> <IndexRoute component={Home}/> <Route path="/repos" component={Repos}> <Route path="/repos/:userName/:repoName" component={Repo}/> </Route> <Route path="/about" component={About}/> </Route> )
src/components/ViewMaster.js
pjkarlik/ReactUI
import React from 'react'; import { resolve } from '../styles'; export default class ViewMaster extends React.Component { static displayName = 'ViewMaster'; static propTypes={ classes: React.PropTypes.object, items: React.PropTypes.object, }; constructor(props) { super(props); this.state = { selected: 0, }; window.addEventListener('resize', this.resize); } componentDidMount() { this.resize(); } resize = () => { const element = this.viewMaster.getBoundingClientRect(); const width = ~~(element.width); const height = ~~(element.height); if (width !== this.state.width || height !== this.state.height) { this.setState({ width, height, }); } }; handleClick = (event, index) => { event.stopPropagation(); const setSlide = index === this.state.selected ? null : index; this.setState({ selected: setSlide, }); }; /* eslint react/jsx-no-bind: 0 */ processSlides = (config) => { const { classes } = this.props; const { slides } = config; const windows = slides.map((item, index) => { const isOpen = this.state.selected; return ( <li key = {`key${index}`} {...resolve(this.props, 'slide', isOpen === index ? 'open' : '', index % 2 === 0 ? 'other' : '')} style={{ width: `${this.state.width}px`, height: `${this.state.height}px` }} > <h4 className={classes.label}>{item.name}</h4> <div className={classes.frame}>{item.child}</div> </li> ); }); const inlineStyle = { width: `${(this.state.width + 10) * slides.length}px`, left: `-${this.state.selected * this.state.width}px`, }; return ( <ul className={classes.content} ref={(ref) => this.viewContent = ref} style={inlineStyle} > {windows} </ul> ); }; processBullets = (config) => { const { classes } = this.props; const { slides } = config; const bullets = slides.map((item, index) => { const isOpen = this.state.selected; return ( <li key = {`key${index}`}> <a href="#" {...resolve(this.props, 'bullet', isOpen === index ? 'active' : '')} onClick = {(event) => {this.handleClick(event, index);}} >{index}</a> </li> ); }); return ( <ul className={classes.bullets}> {bullets} </ul> ); }; updateSlides = (value) => { const { items } = this.props; const offSetX = (value * (this.state.width * (items.slides.length - 1) / this.state.width)); this.viewContent.style.left = `${0 - offSetX}px`; } render() { const { classes, items } = this.props; const slides = this.processSlides(items); const bullets = this.processBullets(items); return ( <div className={classes.masterFrame}> <div className={classes.viewMaster} ref={(ref) => this.viewMaster = ref}> {slides} </div> {bullets} </div> ); } }
docs-ui/components/detailedError.stories.js
gencer/sentry
import React from 'react'; import {storiesOf} from '@storybook/react'; import {action} from '@storybook/addon-actions'; import {withInfo} from '@storybook/addon-info'; import DetailedError from 'sentry-ui/errors/detailedError'; // eslint-disable-next-line storiesOf('DetailedError', module) .add( 'default', withInfo('Displays a detailed error message')(() => ( <DetailedError heading="Error heading" message="Error message" /> )) ) .add( 'with retry', withInfo( 'If `onRetry` callback is supplied, will show a "Retry" button in footer' )(() => ( <DetailedError onRetry={action('onRetry')} heading="Error heading" message="Error message" /> )) ) .add( 'hides support links', withInfo('Hides support links')(() => ( <DetailedError onRetry={action('onRetry')} hideSupportLinks heading="Error heading" message="Error message" /> )) ) .add( 'hides footer', withInfo('Hides footer if no support links or retry')(() => ( <DetailedError hideSupportLinks heading="Error heading" message="Error message" /> )) );
app/javascript/mastodon/features/ui/components/embed_modal.js
Arukas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { FormattedMessage, injectIntl } from 'react-intl'; import api from '../../../api'; @injectIntl export default class EmbedModal extends ImmutablePureComponent { static propTypes = { url: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } state = { loading: false, oembed: null, }; componentDidMount () { const { url } = this.props; this.setState({ loading: true }); api().post('/api/web/embed', { url }).then(res => { this.setState({ loading: false, oembed: res.data }); const iframeDocument = this.iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(res.data.html); iframeDocument.close(); iframeDocument.body.style.margin = 0; this.iframe.width = iframeDocument.body.scrollWidth; this.iframe.height = iframeDocument.body.scrollHeight; }); } setIframeRef = c => { this.iframe = c; } handleTextareaClick = (e) => { e.target.select(); } render () { const { oembed } = this.state; return ( <div className='modal-root__modal embed-modal'> <h4><FormattedMessage id='status.embed' defaultMessage='Embed' /></h4> <div className='embed-modal__container'> <p className='hint'> <FormattedMessage id='embed.instructions' defaultMessage='Embed this status on your website by copying the code below.' /> </p> <input type='text' className='embed-modal__html' readOnly value={oembed && oembed.html || ''} onClick={this.handleTextareaClick} /> <p className='hint'> <FormattedMessage id='embed.preview' defaultMessage='Here is what it will look like:' /> </p> <iframe className='embed-modal__iframe' frameBorder='0' ref={this.setIframeRef} title='preview' /> </div> </div> ); } }
src/svg-icons/hardware/headset.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareHeadset = (props) => ( <SvgIcon {...props}> <path d="M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h3c1.66 0 3-1.34 3-3v-7c0-4.97-4.03-9-9-9z"/> </SvgIcon> ); HardwareHeadset = pure(HardwareHeadset); HardwareHeadset.displayName = 'HardwareHeadset'; HardwareHeadset.muiName = 'SvgIcon'; export default HardwareHeadset;
webpack/scenes/RedHatRepositories/components/RepositoryTypeIcon.js
tstrachota/katello
import React from 'react'; import PropTypes from 'prop-types'; import { ListView, OverlayTrigger, Tooltip } from 'patternfly-react'; import { getTypeIcon } from '../../../services/index'; export default class RepositoryTypeIcon extends React.Component { constructor(props) { super(props); this.tooltipId = `type-tooltip-${props.id}`; } render() { const typeIcon = getTypeIcon(this.props.type); return ( <OverlayTrigger overlay={<Tooltip id={this.tooltipId}>{this.props.type}</Tooltip>} placement="bottom" trigger={['hover', 'focus']} rootClose={false} > <ListView.Icon name={typeIcon.name} size="sm" type={typeIcon.type} /> </OverlayTrigger> ); } } RepositoryTypeIcon.propTypes = { id: PropTypes.number.isRequired, type: PropTypes.string.isRequired, };
src/parser/deathknight/blood/modules/features/InitialMarrowrendCast.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Abilities from 'parser/core/modules/Abilities'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; class InitialMarrowrendCast extends Analyzer { static dependencies = { abilities: Abilities, }; firstMRCast = false; firstMRCastWithoutDRW = false; on_byPlayer_cast(event) { if (event.ability.guid !== SPELLS.MARROWREND.id || this.firstMRCast) { return; } this.firstMRCast = true; if (!this.selectedCombatant.hasBuff(SPELLS.DANCING_RUNE_WEAPON_BUFF.id)) { this.firstMRCastWithoutDRW = true; } } get initialMRThresholds() { return { actual: this.firstMRCastWithoutDRW, isEqual: true, style: 'boolean', }; } suggestions(when) { when(this.initialMRThresholds).isTrue().addSuggestion((suggest, actual, recommended) => { return suggest(<>Use your first <SpellLink id={SPELLS.MARROWREND.id} /> together with <SpellLink id={SPELLS.DANCING_RUNE_WEAPON.id} /> to build up stacks of <SpellLink id={SPELLS.BONE_SHIELD.id} /> faster without wasting as much runes. This will also increase your initial threat-genration as your burst DPS will increase significantly. Don't treat <SpellLink id={SPELLS.DANCING_RUNE_WEAPON.id} /> as a defensive CD unless you really need the parry and increased Runic Power generation defensively.</>) .icon(SPELLS.DANCING_RUNE_WEAPON.icon); }); } } export default InitialMarrowrendCast;
node_modules/@material-ui/core/esm/internal/svg-icons/IndeterminateCheckBox.js
pcclarke/civ-techs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("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-2 10H7v-2h10v2z" }), 'IndeterminateCheckBox');
frontend/assets/js/components/Home.js
ianmilliken/rwf
/* * * FRONTEND * components/Home.js * */ import React from 'react'; import ItemList from './ItemList'; class Home extends React.Component { constructor() { super(); } render() { return ( <div> Results <ItemList /> </div> ) } } export default Home;
src/index.js
almost/react-native-swiper
'use strict' /* react-native-swiper @author leecade<leecade@163.com> */ import React from 'react'; import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Dimensions, } from 'react-native' // Using bare setTimeout, setInterval, setImmediate // and requestAnimationFrame calls is very dangerous // because if you forget to cancel the request before // the component is unmounted, you risk the callback // throwing an exception. import TimerMixin from 'react-timer-mixin' let { width, height } = Dimensions.get('window') /** * Default styles * @type {StyleSheetPropType} */ let styles = StyleSheet.create({ container: { backgroundColor: 'transparent', position: 'relative', }, wrapper: { backgroundColor: 'transparent', }, slide: { backgroundColor: 'transparent', }, pagination_x: { position: 'absolute', bottom: 25, left: 0, right: 0, flexDirection: 'row', flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor:'transparent', }, pagination_y: { position: 'absolute', right: 15, top: 0, bottom: 0, flexDirection: 'column', flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor:'transparent', }, title: { height: 30, justifyContent: 'center', position: 'absolute', paddingLeft: 10, bottom: -30, left: 0, flexWrap: 'nowrap', width: 250, backgroundColor: 'transparent', }, buttonWrapper: { backgroundColor: 'transparent', flexDirection: 'row', position: 'absolute', top: 0, left: 0, flex: 1, paddingHorizontal: 10, paddingVertical: 10, justifyContent: 'space-between', alignItems: 'center' }, buttonText: { fontSize: 50, color: '#007aff', fontFamily: 'Arial', }, }) export default React.createClass({ /** * Props Validation * @type {Object} */ propTypes: { horizontal : React.PropTypes.bool, children : React.PropTypes.node.isRequired, style : View.propTypes.style, pagingEnabled : React.PropTypes.bool, showsHorizontalScrollIndicator : React.PropTypes.bool, showsVerticalScrollIndicator : React.PropTypes.bool, bounces : React.PropTypes.bool, scrollsToTop : React.PropTypes.bool, removeClippedSubviews : React.PropTypes.bool, automaticallyAdjustContentInsets : React.PropTypes.bool, showsPagination : React.PropTypes.bool, showsButtons : React.PropTypes.bool, loop : React.PropTypes.bool, autoplay : React.PropTypes.bool, autoplayTimeout : React.PropTypes.number, autoplayDirection : React.PropTypes.bool, index : React.PropTypes.number, renderPagination : React.PropTypes.func, }, mixins: [TimerMixin], /** * Default props * @return {object} props * @see http://facebook.github.io/react-native/docs/scrollview.html */ getDefaultProps() { return { horizontal : true, pagingEnabled : true, showsHorizontalScrollIndicator : false, showsVerticalScrollIndicator : false, bounces : false, scrollsToTop : false, removeClippedSubviews : true, automaticallyAdjustContentInsets : false, showsPagination : true, showsButtons : false, loop : true, autoplay : false, autoplayTimeout : 2.5, autoplayDirection : true, index : 0, } }, /** * Init states * @return {object} states */ getInitialState() { let props = this.props let initState = { isScrolling: false, autoplayEnd: false, } // Default: horizontal initState.dir = props.horizontal == false ? 'y' : 'x' initState.width = props.width || width initState.height = props.height || height initState.offset = {} return initState }, /** * autoplay timer * @type {null} */ autoplayTimer: null, componentWillMount() { this.props = this.injectState(this.props) }, componentWillReceiveProps(newProps) { let newState = {} newState.total = newProps.children ? (newProps.children.length || 1) : 0 newState.index = newState.total > 1 ? Math.min(this.props.index, newState.total - 1) : 0 newState.offset = {} if(newState.total > 1) { let setup = this.props.loop ? newState.index + 1 : newState.index newState.offset[this.state.dir] = this.state.dir == 'y' ? this.state.height * setup : this.state.width * setup } this.setState(newState); }, componentDidMount() { this.autoplay() }, /** * Automatic rolling */ autoplay() { if(!this.props.autoplay || this.state.isScrolling || this.state.autoplayEnd) return clearTimeout(this.autoplayTimer) this.autoplayTimer = this.setTimeout(() => { if(!this.props.loop && (this.props.autoplayDirection ? this.state.index == this.state.total - 1 : this.state.index == 0)) return this.setState({ autoplayEnd: true }) this.scrollTo(this.props.autoplayDirection ? 1 : -1) }, this.props.autoplayTimeout * 1000) }, /** * Scroll begin handle * @param {object} e native event */ onScrollBegin(e) { // update scroll state this.setState({ isScrolling: true }) this.setTimeout(() => { this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e, this.state, this) }) }, /** * Scroll end handle * @param {object} e native event */ onScrollEnd(e) { // update scroll state this.setState({ isScrolling: false }) this.updateIndex(e.nativeEvent.contentOffset, this.state.dir) // Note: `this.setState` is async, so I call the `onMomentumScrollEnd` // in setTimeout to ensure synchronous update `index` this.setTimeout(() => { this.autoplay() // if `onMomentumScrollEnd` registered will be called here this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e, this.state, this) }) }, /** * Update index after scroll * @param {object} offset content offset * @param {string} dir 'x' || 'y' */ updateIndex(offset, dir) { let state = this.state let index = state.index let diff = offset[dir] - state.offset[dir] let step = dir == 'x' ? state.width : state.height // Do nothing if offset no change. if(!diff) return // Note: if touch very very quickly and continuous, // the variation of `index` more than 1. index = index + diff / step if(this.props.loop) { if(index <= -1) { index = state.total - 1 offset[dir] = step * state.total } else if(index >= state.total) { index = 0 offset[dir] = step } } this.setState({ index: index, offset: offset, }) }, /** * Scroll by index * @param {number} index offset index */ scrollTo(index) { if(this.state.isScrolling) return let state = this.state let diff = (this.props.loop ? 1 : 0) + index + this.state.index let x = 0 let y = 0 if(state.dir == 'x') x = diff * state.width if(state.dir == 'y') y = diff * state.height this.refs.scrollView && this.refs.scrollView.scrollTo(y, x) // update scroll state this.setState({ isScrolling: true, autoplayEnd: false, }) }, /** * Render pagination * @return {object} react-dom */ renderPagination() { // By default, dots only show when `total` > 2 if(this.state.total <= 1) return null let dots = [] for(let i = 0; i < this.state.total; i++) { dots.push(i === this.state.index ? (this.props.activeDot || <View style={{ backgroundColor: '#007aff', width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3, }} />) : (this.props.dot || <View style={{ backgroundColor:'rgba(0,0,0,.2)', width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3, }} />) ) } return ( <View pointerEvents='none' style={[styles['pagination_' + this.state.dir], this.props.paginationStyle]}> {dots} </View> ) }, renderTitle() { let child = this.props.children[this.state.index] let title = child && child.props.title return title ? ( <View style={styles.title}> {this.props.children[this.state.index].props.title} </View> ) : null }, renderNextButton() { let button; if (this.props.loop || this.state.index != this.state.total - 1) { button = this.props.nextButton || <Text style={styles.buttonText}>›</Text> } return ( <TouchableOpacity onPress={() => button !== null && this.scrollTo.call(this, 1)}> <View> {button} </View> </TouchableOpacity> ) }, renderPrevButton() { let button = null if (this.props.loop || this.state.index != 0) { button = this.props.prevButton || <Text style={styles.buttonText}>‹</Text> } return ( <TouchableOpacity onPress={() => button !== null && this.scrollTo.call(this, -1)}> <View> {button} </View> </TouchableOpacity> ) }, renderButtons() { return ( <View pointerEvents='box-none' style={[styles.buttonWrapper, {width: this.state.width, height: this.state.height}, this.props.buttonWrapperStyle]}> {this.renderPrevButton()} {this.renderNextButton()} </View> ) }, /** * Inject state to ScrollResponder * @param {object} props origin props * @return {object} props injected props */ injectState(props) { /* const scrollResponders = [ 'onMomentumScrollBegin', 'onTouchStartCapture', 'onTouchStart', 'onTouchEnd', 'onResponderRelease', ]*/ for(let prop in props) { // if(~scrollResponders.indexOf(prop) if(typeof props[prop] === 'function' && prop !== 'onMomentumScrollEnd' && prop !== 'renderPagination' && prop !== 'onScrollBeginDrag' ) { let originResponder = props[prop] props[prop] = (e) => originResponder(e, this.state, this) } } return props }, /** * Default render * @return {object} react-dom */ render() { let state = this.state let props = this.props let children = props.children let index = state.index let total = state.total let loop = props.loop let dir = state.dir let key = 0 let pages = [] let pageStyle = [{width: state.width, height: state.height}, styles.slide] // For make infinite at least total > 1 if(total > 1) { // Re-design a loop model for avoid img flickering pages = Object.keys(children) if(loop) { pages.unshift(total - 1) pages.push(0) } pages = pages.map((page, i) => <View style={pageStyle} key={i}>{children[page]}</View> ) } else pages = <View style={pageStyle}>{children}</View> return ( <View style={[styles.container, { width: state.width, height: state.height }]}> <ScrollView ref="scrollView" {...props} contentContainerStyle={[styles.wrapper, props.style]} contentOffset={state.offset} onScrollBeginDrag={this.onScrollBegin} onMomentumScrollEnd={this.onScrollEnd}> {pages} </ScrollView> {props.showsPagination && (props.renderPagination ? this.props.renderPagination(state.index, state.total, this) : this.renderPagination())} {this.renderTitle()} {this.props.showsButtons && this.renderButtons()} </View> ) } })
js/jqwidgets/demos/react/app/datatable/fluidsize/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js'; class App extends React.Component { render() { let data = new Array(); let firstNames = [ 'Andrew', 'Nancy', 'Shelley', 'Regina', 'Yoshi', 'Antoni', 'Mayumi', 'Ian', 'Peter', 'Lars', 'Petra', 'Martin', 'Sven', 'Elio', 'Beate', 'Cheryl', 'Michael', 'Guylene' ]; let lastNames = [ 'Fuller', 'Davolio', 'Burke', 'Murphy', 'Nagase', 'Saavedra', 'Ohno', 'Devling', 'Wilson', 'Peterson', 'Winkler', 'Bein', 'Petersen', 'Rossi', 'Vileid', 'Saylor', 'Bjorn', 'Nodier' ]; let productNames = [ 'Black Tea', 'Green Tea', 'Caffe Espresso', 'Doubleshot Espresso', 'Caffe Latte', 'White Chocolate Mocha', 'Cramel Latte', 'Caffe Americano', 'Cappuccino', 'Espresso Truffle', 'Espresso con Panna', 'Peppermint Mocha Twist' ]; let priceValues = [ '2.25', '1.5', '3.0', '3.3', '4.5', '3.6', '3.8', '2.5', '5.0', '1.75', '3.25', '4.0' ]; for (let i = 0; i < 200; i++) { let row = {}; let productindex = Math.floor(Math.random() * productNames.length); let price = parseFloat(priceValues[productindex]); let quantity = 1 + Math.round(Math.random() * 10); row['firstname'] = firstNames[Math.floor(Math.random() * firstNames.length)]; row['lastname'] = lastNames[Math.floor(Math.random() * lastNames.length)]; row['productname'] = productNames[productindex]; row['price'] = price; row['quantity'] = quantity; row['total'] = price * quantity; data[i] = row; } let source = { localData: data, dataType: 'array', dataFields: [ { name: 'firstname', type: 'string' }, { name: 'lastname', type: 'string' }, { name: 'productname', type: 'string' }, { name: 'quantity', type: 'number' }, { name: 'price', type: 'number' }, { name: 'total', type: 'number' } ] }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Name', dataField: 'firstname', width: '20%' }, { text: 'Last Name', dataField: 'lastname', width: '20%' }, { text: 'Product', editable: false, dataField: 'productname', width: '30%' }, { text: 'Quantity', dataField: 'quantity', width: '30%', cellsAlign: 'right', align: 'right' } ]; return ( <JqxDataTable width={'100%'} height={'100%'} source={dataAdapter} pageable={true} columnsResize={true} columns={columns} pagerButtonsCount={3} pageSize={50} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
spec/javascripts/jsx/blueprint_courses/components/CourseFilterSpec.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import * as enzyme from 'enzyme' import CourseFilter from 'jsx/blueprint_courses/components/CourseFilter' import data from '../sampleData' QUnit.module('CourseFilter component') const defaultProps = () => ({ subAccounts: data.subAccounts, terms: data.terms, }) test('renders the CourseFilter component', () => { const tree = enzyme.shallow(<CourseFilter {...defaultProps()} />) const node = tree.find('.bca-course-filter') ok(node.exists()) }) test('onChange fires with search filter when text is entered in search box', (assert) => { const done = assert.async() const props = defaultProps() props.onChange = (filter) => { equal(filter.search, 'giraffe') done() } const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('TextInput input') input.node.value = 'giraffe' input.simulate('change') }) test('onChange fires with term filter when term is selected', (assert) => { const done = assert.async() const props = defaultProps() props.onChange = (filter) => { equal(filter.term, '1') done() } const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('select').at(0) input.node.value = '1' input.simulate('change') }) test('onChange fires with subaccount filter when a subaccount is selected', (assert) => { const done = assert.async() const props = defaultProps() props.onChange = (filter) => { equal(filter.subAccount, '1') done() } const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('select').at(1) input.node.value = '1' input.simulate('change') }) test('onActivate fires when filters are focussed', () => { const props = defaultProps() props.onActivate = sinon.spy() const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('TextInput input') input.simulate('focus') ok(props.onActivate.calledOnce) }) test('onChange not fired when < 3 chars are entered in search text input', (assert) => { const done = assert.async() const props = defaultProps() props.onChange = sinon.spy() const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('input[type="search"]') input.node.value = 'aa' input.simulate('change') setTimeout(() => { equal(props.onChange.callCount, 0) done() }, 0) }) test('onChange fired when 3 chars are entered in search text input', (assert) => { const done = assert.async() const props = defaultProps() props.onChange = sinon.spy() const tree = enzyme.mount(<CourseFilter {...props} />) const input = tree.find('input[type="search"]') input.node.value = 'aaa' input.simulate('change') setTimeout(() => { ok(props.onChange.calledOnce) done() }, 0) })
pages/users/Users.js
mikayel/react-cv
'use strict'; import './Users.css'; import React from 'react' import Header from '../../components/header/Header'; import Navigation from '../../components/navigation/Navigation'; import Footer from '../../components/footer/Footer'; const Users = React.createClass({ render() { return <div className="page_users"> <Header /> <Navigation /> {this.props.children || "Users"} <Footer /> </div> } }) module.exports = Users;
app/javascript/mastodon/components/intersection_observer_article.js
mimumemo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import scheduleIdleTask from '../features/ui/util/schedule_idle_task'; import getRectFromEntry from '../features/ui/util/get_rect_from_entry'; import { is } from 'immutable'; // Diff these props in the "rendered" state const updateOnPropsForRendered = ['id', 'index', 'listLength']; // Diff these props in the "unrendered" state const updateOnPropsForUnrendered = ['id', 'index', 'listLength', 'cachedHeight']; export default class IntersectionObserverArticle extends React.Component { static propTypes = { intersectionObserverWrapper: PropTypes.object.isRequired, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), index: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), listLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), saveHeightKey: PropTypes.string, cachedHeight: PropTypes.number, onHeightChange: PropTypes.func, children: PropTypes.node, }; state = { isHidden: false, // set to true in requestIdleCallback to trigger un-render } shouldComponentUpdate (nextProps, nextState) { const isUnrendered = !this.state.isIntersecting && (this.state.isHidden || this.props.cachedHeight); const willBeUnrendered = !nextState.isIntersecting && (nextState.isHidden || nextProps.cachedHeight); if (!!isUnrendered !== !!willBeUnrendered) { // If we're going from rendered to unrendered (or vice versa) then update return true; } // Otherwise, diff based on props const propsToDiff = isUnrendered ? updateOnPropsForUnrendered : updateOnPropsForRendered; return !propsToDiff.every(prop => is(nextProps[prop], this.props[prop])); } componentDidMount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.observe( id, this.node, this.handleIntersection ); this.componentMounted = true; } componentWillUnmount () { const { intersectionObserverWrapper, id } = this.props; intersectionObserverWrapper.unobserve(id, this.node); this.componentMounted = false; } handleIntersection = (entry) => { this.entry = entry; scheduleIdleTask(this.calculateHeight); this.setState(this.updateStateAfterIntersection); } updateStateAfterIntersection = (prevState) => { if (prevState.isIntersecting !== false && !this.entry.isIntersecting) { scheduleIdleTask(this.hideIfNotIntersecting); } return { isIntersecting: this.entry.isIntersecting, isHidden: false, }; } calculateHeight = () => { const { onHeightChange, saveHeightKey, id } = this.props; // save the height of the fully-rendered element (this is expensive // on Chrome, where we need to fall back to getBoundingClientRect) this.height = getRectFromEntry(this.entry).height; if (onHeightChange && saveHeightKey) { onHeightChange(saveHeightKey, id, this.height); } } hideIfNotIntersecting = () => { if (!this.componentMounted) { return; } // When the browser gets a chance, test if we're still not intersecting, // and if so, set our isHidden to true to trigger an unrender. The point of // this is to save DOM nodes and avoid using up too much memory. // See: https://github.com/tootsuite/mastodon/issues/2900 this.setState((prevState) => ({ isHidden: !prevState.isIntersecting })); } handleRef = (node) => { this.node = node; } render () { const { children, id, index, listLength, cachedHeight } = this.props; const { isIntersecting, isHidden } = this.state; if (!isIntersecting && (isHidden || cachedHeight)) { return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} style={{ height: `${this.height || cachedHeight}px`, opacity: 0, overflow: 'hidden' }} data-id={id} tabIndex='0' > {children && React.cloneElement(children, { hidden: true })} </article> ); } return ( <article ref={this.handleRef} aria-posinset={index + 1} aria-setsize={listLength} data-id={id} tabIndex='0'> {children && React.cloneElement(children, { hidden: false })} </article> ); } }
httpdocs/theme/react/hooks-app/opendesktop-home/components/ChatContainer.js
KDE/ocs-webserver
import React, { Component } from 'react'; class ChatContainer extends Component { constructor(props){ super(props); this.chatUrl = '/json/chat'; this.avatarUrl= 'https://chat.opendesktop.org/_matrix/media/v1/thumbnail'; this.state = {items:[]}; } componentDidMount() { fetch(this.chatUrl) .then(response => response.json()) .then(data => { this.setState({items:data}); }); } render(){ let container, members; if (this.state.items){ const feedItems = this.state.items.map((fi,index) => { if(fi.members){ let mb=Object.values(fi.members); if(mb.length>0){ members = mb.slice(0,4).map((m,index) => { let imgAvatar; if(m.avatar_url){ imgAvatar = <img src={this.avatarUrl+m.avatar_url.substring(5)+'?width=39&height=39&method=crop'}></img> } return ( <div className="chatUser"> {imgAvatar} <div className="name"> {m.display_name} </div> </div> ) } ); } if(fi.guest_can_join==false) { return ( <li key={index} className="chatMember"> <a href={this.roomUrl+fi.room_id} > join our chat {(fi.canonical_alias)?fi.canonical_alias.substring(0,fi.canonical_alias.indexOf(':'))+' ('+fi.num_joined_members+')':''} </a> {members} </li> ) } } }); container = <ul>{feedItems}</ul>; } return ( <div id="chat-container" className="panelContainer"> <div className="title"><a href="https://chat.opendesktop.org">Riot Chat</a> </div> {container} </div> ) } } export default ChatContainer;
cdap-ui/app/cdap/components/CaskWizards/StreamCreateWithUpload/SchemaStep/index.js
caskdata/cdap
/* * Copyright © 2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import React from 'react'; import {connect, Provider} from 'react-redux'; import {Col, FormGroup, Label, Form} from 'reactstrap'; import T from 'i18n-react'; import SelectWithOptions from 'components/SelectWithOptions'; import SimpleSchema from 'components/SimpleSchema'; import CreateStreamWithUploadStore, { defaultSchemaFormats } from 'services/WizardStores/CreateStreamWithUpload/CreateStreamWithUploadStore'; import CreateStreamWithUploadActions from 'services/WizardStores/CreateStream/CreateStreamActions'; const mapStateToSchemaTypeProps = (state) => { return { value: state.schema.format, options: defaultSchemaFormats }; }; const mapDispatchToSchemaTypeProps = (dispatch) => { return { onChange: (e) => (dispatch({ type: CreateStreamWithUploadActions.setSchemaFormat, payload: { format: e.target.value} })) }; }; const SchemaType = connect( mapStateToSchemaTypeProps, mapDispatchToSchemaTypeProps )(SelectWithOptions); const SimpleSchemaWrapper = connect( state => { return { schema: state.schema.value, }; }, dispatch => { return { onSchemaChange: (schema) => { dispatch({ type: CreateStreamWithUploadActions.setSchema, payload: { schema } }); } }; } )(SimpleSchema); export default function SchemaStep() { return ( <Provider store={CreateStreamWithUploadStore}> <Form className="form-horizontal" onSubmit={(e) => { e.preventDefault(); return false; }} > <FormGroup> <Col xs="2"> <Label className="control-label">{T.translate('commons.formatLabel')}</Label> </Col> <Col xs="4"> <SchemaType className="input-sm"/> </Col> </FormGroup> <FormGroup> <Col xs="12"> <Label className="control-label">{T.translate('commons.schemaLabel')}</Label> </Col> <Col xs="12"> <SimpleSchemaWrapper /> </Col> </FormGroup> </Form> </Provider> ); }
js/components/Gallery.js
fractal-mind/portfolio
import React from 'react'; import GalleryCard from './GalleryCard'; class Gallery extends React.Component { render(){ return( <div className="galleryContainer container"> <p className="galleryHeader">Portfolio</p> {this.props.list.map(site => <GalleryCard key={site.key} name={site.name} url={site.url} info={site.info} thumb={site.thumb}/>)} </div> ) } } export default Gallery;
client/src/index.js
compewter/VeAL
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; import 'semantic-ui-css/semantic.min.css'; import {Provider} from 'react-redux'; import configureStore from './store'; import initialState from './initialState' ReactDOM.render( <Provider store={configureStore(initialState)}> <App /> </Provider>, document.getElementById('root') );
src/svg-icons/action/bug-report.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBugReport = (props) => ( <SvgIcon {...props}> <path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/> </SvgIcon> ); ActionBugReport = pure(ActionBugReport); ActionBugReport.displayName = 'ActionBugReport'; ActionBugReport.muiName = 'SvgIcon'; export default ActionBugReport;
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/Paper/Page.js
pbogdan/react-flux-mui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import paperReadmeText from './README'; import PaperExampleSimple from './ExampleSimple'; import paperExampleSimpleCode from '!raw!./ExampleSimple'; import PaperExampleRounded from './ExampleRounded'; import paperExampleRoundedCode from '!raw!./ExampleRounded'; import PaperExampleCircle from './ExampleCircle'; import paperExampleCircleCode from '!raw!./ExampleCircle'; import paperCode from '!raw!material-ui/Paper/Paper'; const descriptions = { simple: 'Paper examples showing the range of `zDepth`.', rounded: 'Corners are rounded by default. Set the `rounded` property to `false` for square corners.', circle: 'Set the `circle` property for circular Paper.', }; const PaperPage = () => ( <div> <Title render={(previousTitle) => `Paper - ${previousTitle}`} /> <MarkdownElement text={paperReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={paperExampleSimpleCode} > <PaperExampleSimple /> </CodeExample> <CodeExample title="Non-rounded corners" description={descriptions.rounded} code={paperExampleRoundedCode} > <PaperExampleRounded /> </CodeExample> <CodeExample title="Circular Paper" description={descriptions.circle} code={paperExampleCircleCode} > <PaperExampleCircle /> </CodeExample> <PropTypeDescription code={paperCode} /> </div> ); export default PaperPage;
src/package/plugins/slate-alignment-plugin/AlignmentRightButton.js
abobwhite/slate-editor
import React from 'react' import classnames from 'classnames' import FontAwesome from 'react-fontawesome' import { Button} from '../../components/button' import { alignmentMarkStrategy, hasMark, getMark } from './AlignmentUtils' const AlignmentRightButton = ({ state, onChange, changeState, className, style, type }) => ( <Button style={style} type={type} onClick={e => onChange(alignmentMarkStrategy(state.change(), 'right'))} className={classnames( 'slate-alignment-plugin--button', { active: hasMark(state) && getMark(state).data.get('align') === 'right' }, className, )} > <FontAwesome name="align-right" /> </Button> ) export default AlignmentRightButton
fields/components/DateInput__OLD.js
Pylipala/keystone
import moment from 'moment'; import Pikaday from 'pikaday'; import React from 'react'; import { FormInput } from 'elemental'; module.exports = React.createClass({ displayName: 'DateInput', // set default properties getDefaultProps: function() { return { format: 'YYYY-MM-DD' }; }, getInitialState: function() { return { value: this.props.value, id: Math.round(Math.random() * 100000) }; }, componentWillReceiveProps: function(newProps) { if (newProps.value === this.state.value) return; this.setState({ value: newProps.value }); this.picker.setMoment(moment(newProps.value, this.props.format)); }, componentDidMount: function() { this.picker = new Pikaday({ field: this.getDOMNode(), format: this.props.format, yearRange: this.props.yearRange, onSelect: (date) => { // eslint-disable-line no-unused-vars if (this.props.onChange && this.picker.toString() !== this.props.value) { this.props.onChange(this.picker.toString()); } } }); }, componentWillUnmount: function() { this.picker.destroy(); }, handleChange: function(e) { if (e.target.value === this.state.value) return; this.setState({ value: e.target.value }); }, handleBlur: function(e) { // eslint-disable-line no-unused-vars if (this.state.value === this.props.value) return; var newValue = moment(this.state.value, this.props.format); if (newValue.isValid()) { this.picker.setMoment(newValue); } else { this.picker.setDate(null); if (this.props.onChange) this.props.onChange(''); } }, render: function() { return <FormInput name={this.props.name} value={this.state.value} placeholder={this.props.format} onChange={this.handleChange} onBlur={this.handleBlur} autoComplete="off" />; } });
src/client.js
muriloreis/drfarm
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import UniversalRouter from 'universal-router'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import history from './core/history'; import App from './components/App'; import { updateMeta } from './core/DOMUtils'; import { ErrorReporter, deepForceUpdate } from './core/devUtils'; // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, }; // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration const scrollPositionsHistory = {}; if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } let onRenderComplete = function initialRenderComplete() { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); onRenderComplete = function renderComplete(route, location) { document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }; }; // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); const container = document.getElementById('app'); let appInstance; let currentLocation = history.location; let routes = require('./routes').default; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; try { // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await UniversalRouter.resolve(routes, { path: location.pathname, query: queryString.parse(location.search), }); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } appInstance = ReactDOM.render( <App context={context}>{route.component}</App>, container, () => onRenderComplete(route, location), ); } catch (error) { // Display the error in full-screen for development mode if (__DEV__) { appInstance = null; document.title = `Error: ${error.message}`; ReactDOM.render(<ErrorReporter error={error} />, container); throw error; } console.error(error); // eslint-disable-line no-console // Do a full page reload if error occurs during client-side navigation if (action && currentLocation.key === location.key) { window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Handle errors that might happen after rendering // Display the error in full-screen for development mode if (__DEV__) { window.addEventListener('error', (event) => { appInstance = null; document.title = `Runtime Error: ${event.error.message}`; ReactDOM.render(<ErrorReporter error={event.error} />, container); }); } // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./routes', () => { routes = require('./routes').default; // eslint-disable-line global-require if (appInstance) { try { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } catch (error) { appInstance = null; document.title = `Hot Update Error: ${error.message}`; ReactDOM.render(<ErrorReporter error={error} />, container); return; } } onLocationChange(currentLocation); }); }
docs/app/Examples/views/Feed/Types/Basic.js
jamiehill/stardust
import React from 'react' import { Feed } from 'stardust' const { Content, Date, Event, Extra, Label, Like, Meta, Summary, User } = Feed const Basic = () => { return ( <Feed> <Event> <Label> <img src='http://semantic-ui.com/images/avatar/small/elliot.jpg' /> </Label> <Content> <Summary> <User>Elliot Fu</User> added you as a friend <Date>1 Hour Ago</Date> </Summary> <Meta> <Like icon='like'>4 Likes</Like> </Meta> </Content> </Event> <Event> <Label image='http://semantic-ui.com/images/avatar/small/helen.jpg' /> <Content> <Summary> <a>Helen Troy</a> added <a>2 new illustrations</a> <Date>4 days ago</Date> </Summary> <Extra images> <a><img src='http://semantic-ui.com/images/wireframe/image.png' /></a> <a><img src='http://semantic-ui.com/images/wireframe/image.png' /></a> </Extra> <Meta> <Like>1 Like</Like> </Meta> </Content> </Event> <Event> <Label image='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> <Content> <Summary date='2 Days Ago'> <User>Jenny Hess</User> added you as a friend </Summary> <Meta like='8 Likes' /> </Content> </Event> <Event> <Label image='http://semantic-ui.com/images/avatar/small/joe.jpg' /> <Content> <Summary date='3 days ago'> <a>Joe Henderson</a> posted on his page </Summary> <Extra text> Ours is a life of constant reruns. We're always circling back to where we'd we started, then starting all over again. Even if we don't run extra laps that day, we surely will come back for more of the same another day soon. </Extra> <Meta like='5 Likes' /> </Content> </Event> <Event> <Label image='http://semantic-ui.com/images/avatar/small/justen.jpg' /> <Content> <Summary date='4 days ago'> <a>Justen Kitsune</a> added <a>2 new photos</a> of you </Summary> <Extra images> <a><img src='http://semantic-ui.com/images/wireframe/image.png' /></a> <a><img src='http://semantic-ui.com/images/wireframe/image.png' /></a> </Extra> <Meta like='41 Likes' /> </Content> </Event> </Feed> ) } export default Basic
versions/3-redux/1-containers/client/src/components/Counter.js
hamczu/techsummit-web2016
import React from 'react' export default ({ onClick, count }) => ( <div> <button onClick={onClick}>click me!</button> <span>{count}</span> </div> )
app/index.js
JSVillage/military-families
import React from 'react'; import {render} from 'react-dom'; import {Router, hashHistory} from 'react-router'; import routes from './routes'; render(<Router history={hashHistory} routes={routes} />, document.getElementById('app'));
es/components/Chat/Markup/Link.js
welovekpop/uwave-web-welovekpop.club
import _extends from "@babel/runtime/helpers/builtin/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import shortenUrl from 'shorten-url'; var Link = function Link(_ref) { var children = _ref.children, href = _ref.href, props = _objectWithoutProperties(_ref, ["children", "href"]); return React.createElement("a", _extends({ href: href, title: href, target: "_blank", rel: "noopener noreferrer" }, props), shortenUrl(children, 60)); }; Link.propTypes = process.env.NODE_ENV !== "production" ? { children: PropTypes.string.isRequired, href: PropTypes.string.isRequired } : {}; export default Link; //# sourceMappingURL=Link.js.map
lib/blocks/h2.js
pairyo/kattappa
import React from 'react'; import QuillComponent from '../components/quill'; import BlockText from './text'; class BlockH2 extends BlockText.React { render() { return ( <h2 className="katap-block katap-h2"> <QuillComponent showToolbar={false} formats={[]} content={this.props.content} captureReturn={this.captureReturn} onContentChanged={this.onContentChanged} /> </h2> ); } } let H2 = { Name: 'h2', React: BlockH2, Icon: '', Empty: function() { return ''; }, Description: 'Heading 2', isEmpty: function(content) { return (content.replace(/(<([^>]+)>)/ig,'') === ''); } }; export default H2;
src/components/templates/ArtworkCreate/index.js
ygoto3/artwork-manager
// @flow import React, { Component } from 'react'; import { ArtworkForm } from '../../molecules/ArtworkForm'; export type ArtworkCreateProps = { createArtwork: (artwork: Artwork) => void; }; const validators = { title: (t) => t.value.length ? null : 'too short', }; export class ArtworkCreate extends Component<*, ArtworkCreateProps, *> { onClickSubmit: Function; constructor() { super(); this.onClickSubmit = this.onClickSubmit.bind(this); } render() { return ( <ArtworkForm onClickSubmit={this.onClickSubmit} validators={validators} /> ); } onClickSubmit(e: SyntheticEvent, artwork: Artwork) { this.props.createArtwork(artwork); } }
src/svg-icons/hardware/desktop-windows.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDesktopWindows = (props) => ( <SvgIcon {...props}> <path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z"/> </SvgIcon> ); HardwareDesktopWindows = pure(HardwareDesktopWindows); HardwareDesktopWindows.displayName = 'HardwareDesktopWindows'; HardwareDesktopWindows.muiName = 'SvgIcon'; export default HardwareDesktopWindows;
src/main.js
scubism/react_todo_web
/** * App entry point */ // Polyfill import 'babel-polyfill'; // Libraries import React from 'react'; import ReactDOM from 'react-dom'; import { match, Router, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import { trigger } from 'redial'; // Routes import Routes from './common/components/Routes'; import { configureStore } from './common/store'; import createSaga from './common/createSaga'; // Base styling import './common/base.css'; if (process.env.BROWSER) { require("loaders.css/loaders.min.css") } // ID of the DOM element to mount app on const DOM_APP_EL_ID = 'app'; const initialState = window.INITIAL_STATE || {}; if (window.SERVER_MESSAGES && window.SERVER_MESSAGES.length > 0) { window.SERVER_MESSAGES.forEach((message) => { alert(message); }) } const { pathname, search, hash } = window.location; const location = `${pathname}${search}${hash}`; const store = configureStore(initialState); store.runSaga(createSaga(store.getState)) const { dispatch } = store; // Pull child routes using match. Adjust Router for vanilla webpack HMR, // in development using a new key every time there is an edit. match({ routes: Routes, location: location }, () => { // Render app with Redux and router context to container element. // We need to have a random in development because of `match`'s dependency on // `routes.` Normally, we would want just one file from which we require `routes` from. ReactDOM.render( <Provider store={store}> <Router routes={Routes} history={browserHistory} key={Math.random()}/> </Provider>, document.getElementById(DOM_APP_EL_ID) ); }); browserHistory.listen(location => { // Match routes based on location object: match({ routes: Routes, location: location }, (error, redirectLocation, renderProps) => { // Get array of route handler components: const { components } = renderProps; // Define locals to be provided to all lifecycle hooks: const locals = { path: renderProps.location.pathname, query: renderProps.location.query, params: renderProps.params, // Allow lifecycle hooks to dispatch Redux actions: dispatch, }; // Don't fetch data for initial route, server has already done the work: if (window.INITIAL_STATE) { // Delete initial data so that subsequent data fetches can occur: delete window.INITIAL_STATE; } else { // Fetch mandatory data dependencies for 2nd route change onwards: trigger('fetch', components, locals); } // Fetch deferred, client-only data dependencies: trigger('defer', components, locals); trigger('done', components, locals); }); });
springboot/GReact/src/main/resources/static/app/components/navigation/components/MinifyMenu.js
ezsimple/java
/** * Created by griga on 11/30/15. */ import React from 'react' let $body = $('body'); let MinifyMenu = React.createClass({ toggle: function () { if (!$body.hasClass("menu-on-top")) { $body.toggleClass("minified"); $body.removeClass("hidden-menu"); $('html').removeClass("hidden-menu-mobile-lock"); } }, render: function () { return ( <span className="minifyme" data-action="minifyMenu" onClick={this.toggle}> <i className="fa fa-arrow-circle-left hit"/> </span> ) } }); export default MinifyMenu
src/app/containers/HomeContainer.js
paulawasylow/e-commerce-react-app
import React, { Component } from 'react'; import { data } from '../API/data'; import ProductHomePage from '../components/ProductHomePage'; class HomeContainer extends Component { static propTypes = { products: React.PropTypes.array, product: React.PropTypes.object } state = { products: [] } componentDidMount() { this.setState({products: data }); } render() { const { products } = this.state; const getProductsHomePage = products.map(product => { return (<ProductHomePage key={product.id} product={product} {...this.props} />); }); const takeLastFourProducts = getProductsHomePage.slice(-4); return ( <div className="wrapper"> <div className="home-page__header"> <div className="panel home-page__header--title"> <h1>New products</h1> </div> </div> <div className="panel__list"> {takeLastFourProducts} </div> </div> ); } } export default HomeContainer;
src/svg-icons/file/cloud-upload.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudUpload = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); FileCloudUpload = pure(FileCloudUpload); FileCloudUpload.displayName = 'FileCloudUpload'; FileCloudUpload.muiName = 'SvgIcon'; export default FileCloudUpload;
scripts/donationSettings.js
diakov2100/YaStreamDesktop
import React from 'react'; import ReactDOM from 'react-dom'; import DonationSettingsMain from '../views/donationSettings/donationSettingsMain.jsx' const $ = require('./jquery.js') const {ipcRenderer} = require('electron') const remote = require('electron').remote window.onload = function(){ ReactDOM.render(<DonationSettingsMain />, document.getElementsByClassName('container')[0]); let syntes = false let color = 'rgba(0, 0, 0, 0)' $('#color-picker').on('change', function(){ color = $(this).val() }) var val = ($('input[type="range"]').val() - $('input[type="range"]').attr('min')) / ($('input[type="range"]').attr('max') - $('input[type="range"]').attr('min')); $('#inputHeight').val(60*val) $('input[type="range"]').on("change mousemove input", function () { var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min')); $(this).css('background-image', '-webkit-gradient(linear, left top, right top, ' + 'color-stop(' + val + ', #f3c647), ' + 'color-stop(' + val + ', #979797)' + ')' ); let num = 60*val if (num == 31.000000000000004){ num = 31 } $('.max').text(num + ' сек.') }) $('input[type="checkbox"]').on('click', function(){ if (!syntes){ syntes = true } else { syntes = false } }) /* document.getElementsByClassName('btn-save')[0].onclick = () => { localStorage.setItem('syntes', syntes) localStorage.setItem('alertLengthSec', $('#inputHeight').val()) localStorage.setItem('patternAlert', $('.text input').val()) if ($('#color-picker').val() == ""){ localStorage.setItem('alertBackColor', 'rgba(0,0,0,0)') } else { localStorage.setItem('alertBackColor', $('#color-picker').val()) } ipcRenderer.send('donationSettings-closed') }*/ let returnBtn = document.getElementsByClassName('return')[0] returnBtn.onclick = () => { remote.getCurrentWindow().close() } returnBtn.onmouseover = function(){ this.childNodes[0].childNodes[0].src = '../images/arrowActive.png' } returnBtn.onmouseleave = function(){ this.childNodes[0].childNodes[0].src = '../images/bitmap.png' } }
admin/client/App/screens/Home/components/Section.js
trentmillar/keystone
import React from 'react'; import getRelatedIconClass from '../utils/getRelatedIconClass'; class Section extends React.Component { render () { const iconClass = this.props.icon || getRelatedIconClass(this.props.id); return ( <div className="dashboard-group" data-section-label={this.props.label}> <div className="dashboard-group__heading"> <span className={`dashboard-group__heading-icon ${iconClass}`} /> {this.props.label} </div> {this.props.children} </div> ); } } Section.propTypes = { children: React.PropTypes.element.isRequired, icon: React.PropTypes.string, id: React.PropTypes.string, label: React.PropTypes.string.isRequired, }; export default Section;
chrome/extension/inject.js
tariksahni/scraper.ooo
import React, { Component } from 'react'; import { render } from 'react-dom'; import Dock from 'react-dock'; class InjectApp extends Component { constructor(props) { super(props); this.state = { isVisible: false }; } buttonOnClick = () => { this.setState({ isVisible: !this.state.isVisible }); }; render() { return ( <div> <button onClick={this.buttonOnClick}> Open TodoApp </button> <Dock position="right" dimMode="transparent" defaultSize={0.4} isVisible={this.state.isVisible} > <iframe style={{ width: '100%', height: '100%', }} frameBorder={0} allowTransparency="true" src={chrome.extension.getURL(`inject.html?protocol=${location.protocol}`)} /> </Dock> </div> ); } } window.addEventListener('load', () => { const injectDOM = document.createElement('div'); injectDOM.className = 'inject-react-example'; injectDOM.style.textAlign = 'center'; document.body.appendChild(injectDOM); render(<InjectApp />, injectDOM); });
docs/pages/api-docs/timeline-item.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/timeline-item'; const requireRaw = require.context('!raw-loader!./', false, /\/timeline-item\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
RNComponents/template.js
Jonham/ReactNative-EnjoySuffering
// this file works as a template file for any new ReactNative component import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class COMPONENT_NAME extends Component { render() { return ( <View style={styles.parent}> <Text style={styles.title__text}> New Component </Text> </View> ); } } const styles = StyleSheet.create({ parent: { alignItems: 'center', justifyContent: 'center', flex: 1, }, title__text: { color: "black", fontSize: 20 } });
assets/js/components/StripEntities/index.js
mlapierre/Winds
import React from 'react' var Entities = require('html-entities').AllHtmlEntities, entities = new Entities(), normalizeWhitespace = require('normalize-html-whitespace') export default props => ( <span> {entities.decode(normalizeWhitespace(props.children))} </span> ) require('./styles.scss')
src/svg-icons/action/view-headline.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewHeadline = (props) => ( <SvgIcon {...props}> <path d="M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z"/> </SvgIcon> ); ActionViewHeadline = pure(ActionViewHeadline); ActionViewHeadline.displayName = 'ActionViewHeadline'; ActionViewHeadline.muiName = 'SvgIcon'; export default ActionViewHeadline;
src/routes/dashboard/components/numberCard.js
shaohuawang2015/goldbeans-admin
import React from 'react' import PropTypes from 'prop-types' import { Icon, Card } from 'antd' import CountUp from 'react-countup' import styles from './numberCard.less' function NumberCard ({ icon, color, title, number, countUp }) { return ( <Card className={styles.numberCard} bordered={false} bodyStyle={{ padding: 0 }}> <Icon className={styles.iconWarp} style={{ color }} type={icon} /> <div className={styles.content}> <p className={styles.title}>{title || 'No Title'}</p> <p className={styles.number}> <CountUp start={0} end={number} duration={2.75} useEasing useGrouping separator="," {...countUp || {}} /> </p> </div> </Card> ) } NumberCard.propTypes = { icon: PropTypes.string, color: PropTypes.string, title: PropTypes.string, number: PropTypes.number, countUp: PropTypes.object, } export default NumberCard
source/Table/defaultHeaderRenderer.js
edulan/react-virtualized
/** @flow */ import React from 'react' import SortIndicator from './SortIndicator' import type { HeaderRendererParams } from './types' /** * Default table header renderer. */ export default function defaultHeaderRenderer ({ columnData, dataKey, disableSort, label, sortBy, sortDirection }: HeaderRendererParams) { const showSortIndicator = sortBy === dataKey const children = [ <span className='ReactVirtualized__Table__headerTruncatedText' key='label' title={label} > {label} </span> ] if (showSortIndicator) { children.push( <SortIndicator key='SortIndicator' sortDirection={sortDirection} /> ) } return children }
admin/client/App/screens/List/index.js
danielmahon/keystone
/** * The list view is a paginated table of all items in the list. It can show a * variety of information about the individual items in columns. */ import React from 'react'; // import { findDOMNode } from 'react-dom'; // TODO re-implement focus when ready import numeral from 'numeral'; import { connect } from 'react-redux'; import { BlankState, Center, Container, Glyph, GlyphButton, Pagination, Spinner, } from '../../elemental'; import ListFilters from './components/Filtering/ListFilters'; import ListHeaderTitle from './components/ListHeaderTitle'; import ListHeaderToolbar from './components/ListHeaderToolbar'; import ListManagement from './components/ListManagement'; import ConfirmationDialog from '../../shared/ConfirmationDialog'; import CreateForm from '../../shared/CreateForm'; import FlashMessages from '../../shared/FlashMessages'; import ItemsTable from './components/ItemsTable/ItemsTable'; import UpdateForm from './components/UpdateForm'; import { plural as pluralize } from '../../../utils/string'; import { listsByPath } from '../../../utils/lists'; import { checkForQueryChange } from '../../../utils/queryParams'; import { deleteItems, setActiveSearch, setActiveSort, setCurrentPage, selectList, clearCachedQuery, } from './actions'; import { deleteItem, } from '../Item/actions'; const ESC_KEY_CODE = 27; const ListView = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { confirmationDialog: { isOpen: false, }, checkedItems: {}, constrainTableWidth: true, manageMode: false, showCreateForm: false, showUpdateForm: false, }; }, componentWillMount () { // When we directly navigate to a list without coming from another client // side routed page before, we need to initialize the list and parse // possibly specified query parameters this.props.dispatch(selectList(this.props.params.listId)); const isNoCreate = this.props.lists.data[this.props.params.listId].nocreate; const shouldOpenCreate = this.props.location.search === '?create'; this.setState({ showCreateForm: (shouldOpenCreate && !isNoCreate) || Keystone.createFormErrors, }); }, componentWillReceiveProps (nextProps) { // We've opened a new list from the client side routing, so initialize // again with the new list id const isReady = this.props.lists.ready && nextProps.lists.ready; if (isReady && checkForQueryChange(nextProps, this.props)) { this.props.dispatch(selectList(nextProps.params.listId)); } }, componentWillUnmount () { this.props.dispatch(clearCachedQuery()); }, // ============================== // HEADER // ============================== // Called when a new item is created onCreate (item) { // Hide the create form this.toggleCreateModal(false); // Redirect to newly created item path const list = this.props.currentList; this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`); }, createAutocreate () { const list = this.props.currentList; list.createItem(null, (err, data) => { if (err) { // TODO Proper error handling alert('Something went wrong, please try again!'); console.log(err); } else { this.context.router.push(`${Keystone.adminPath}/${list.path}/${data.id}`); } }); }, updateSearch (e) { this.props.dispatch(setActiveSearch(e.target.value)); }, handleSearchClear () { this.props.dispatch(setActiveSearch('')); // TODO re-implement focus when ready // findDOMNode(this.refs.listSearchInput).focus(); }, handleSearchKey (e) { // clear on esc if (e.which === ESC_KEY_CODE) { this.handleSearchClear(); } }, handlePageSelect (i) { // If the current page index is the same as the index we are intending to pass to redux, bail out. if (i === this.props.lists.page.index) return; return this.props.dispatch(setCurrentPage(i)); }, toggleManageMode (filter = !this.state.manageMode) { this.setState({ manageMode: filter, checkedItems: {}, }); }, toggleUpdateModal (filter = !this.state.showUpdateForm) { this.setState({ showUpdateForm: filter, }); }, massUpdate () { // TODO: Implement update multi-item console.log('Update ALL the things!'); }, massDelete () { const { checkedItems } = this.state; const list = this.props.currentList; const itemCount = pluralize(checkedItems, ('* ' + list.singular.toLowerCase()), ('* ' + list.plural.toLowerCase())); const itemIds = Object.keys(checkedItems); this.setState({ confirmationDialog: { isOpen: true, label: 'Delete', body: ( <div> Are you sure you want to delete {itemCount}? <br /> <br /> This cannot be undone. </div> ), onConfirmation: () => { this.props.dispatch(deleteItems(itemIds)); this.toggleManageMode(); this.removeConfirmationDialog(); }, }, }); }, handleManagementSelect (selection) { if (selection === 'all') this.checkAllItems(); if (selection === 'none') this.uncheckAllTableItems(); if (selection === 'visible') this.checkAllTableItems(); return false; }, renderConfirmationDialog () { const props = this.state.confirmationDialog; return ( <ConfirmationDialog confirmationLabel={props.label} isOpen={props.isOpen} onCancel={this.removeConfirmationDialog} onConfirmation={props.onConfirmation} > {props.body} </ConfirmationDialog> ); }, renderManagement () { const { checkedItems, manageMode, selectAllItemsLoading } = this.state; const { currentList } = this.props; return ( <ListManagement checkedItemCount={Object.keys(checkedItems).length} handleDelete={this.massDelete} handleSelect={this.handleManagementSelect} handleToggle={() => this.toggleManageMode(!manageMode)} isOpen={manageMode} itemCount={this.props.items.count} itemsPerPage={this.props.lists.page.size} nodelete={currentList.nodelete} noedit={currentList.noedit} selectAllItemsLoading={selectAllItemsLoading} /> ); }, renderPagination () { const items = this.props.items; if (this.state.manageMode || !items.count) return; const list = this.props.currentList; const currentPage = this.props.lists.page.index; const pageSize = this.props.lists.page.size; return ( <Pagination currentPage={currentPage} onPageSelect={this.handlePageSelect} pageSize={pageSize} plural={list.plural} singular={list.singular} style={{ marginBottom: 0 }} total={items.count} limit={10} /> ); }, renderHeader () { const items = this.props.items; const { autocreate, nocreate, plural, singular } = this.props.currentList; return ( <Container style={{ paddingTop: '2em' }}> <ListHeaderTitle activeSort={this.props.active.sort} availableColumns={this.props.currentList.columns} handleSortSelect={this.handleSortSelect} title={` ${numeral(items.count).format()} ${pluralize(items.count, ' ' + singular, ' ' + plural)} `} /> <ListHeaderToolbar // common dispatch={this.props.dispatch} list={listsByPath[this.props.params.listId]} // expand expandIsActive={!this.state.constrainTableWidth} expandOnClick={this.toggleTableWidth} // create createIsAvailable={!nocreate} createListName={singular} createOnClick={autocreate ? this.createAutocreate : this.openCreateModal} // search searchHandleChange={this.updateSearch} searchHandleClear={this.handleSearchClear} searchHandleKeyup={this.handleSearchKey} searchValue={this.props.active.search} // filters filtersActive={this.props.active.filters} filtersAvailable={this.props.currentList.columns.filter((col) => ( col.field && col.field.hasFilterMethod) || col.type === 'heading' )} // columns columnsActive={this.props.active.columns} columnsAvailable={this.props.currentList.columns} /> <ListFilters dispatch={this.props.dispatch} filters={this.props.active.filters} /> </Container> ); }, // ============================== // TABLE // ============================== checkTableItem (item, e) { e.preventDefault(); const newCheckedItems = { ...this.state.checkedItems }; const itemId = item.id; if (this.state.checkedItems[itemId]) { delete newCheckedItems[itemId]; } else { newCheckedItems[itemId] = true; } this.setState({ checkedItems: newCheckedItems, }); }, checkAllTableItems () { const checkedItems = {}; this.props.items.results.forEach(item => { checkedItems[item.id] = true; }); this.setState({ checkedItems: checkedItems, }); }, checkAllItems () { const checkedItems = { ...this.state.checkedItems }; // Just in case this API call takes a long time, we'll update the select all button with // a spinner. this.setState({ selectAllItemsLoading: true }); var self = this; this.props.currentList.loadItems({ expandRelationshipFilters: false, filters: {} }, function (err, data) { data.results.forEach(item => { checkedItems[item.id] = true; }); self.setState({ checkedItems: checkedItems, selectAllItemsLoading: false, }); }); }, uncheckAllTableItems () { this.setState({ checkedItems: {}, }); }, deleteTableItem (item, e) { if (e.altKey) { this.props.dispatch(deleteItem(item.id)); return; } e.preventDefault(); this.setState({ confirmationDialog: { isOpen: true, label: 'Delete', body: ( <div> Are you sure you want to delete <strong>{item.name}</strong>? <br /> <br /> This cannot be undone. </div> ), onConfirmation: () => { this.props.dispatch(deleteItem(item.id)); this.removeConfirmationDialog(); }, }, }); }, removeConfirmationDialog () { this.setState({ confirmationDialog: { isOpen: false, }, }); }, toggleTableWidth () { this.setState({ constrainTableWidth: !this.state.constrainTableWidth, }); }, // ============================== // COMMON // ============================== handleSortSelect (path, inverted) { if (inverted) path = '-' + path; this.props.dispatch(setActiveSort(path)); }, toggleCreateModal (visible) { this.setState({ showCreateForm: visible, }); }, openCreateModal () { this.toggleCreateModal(true); }, closeCreateModal () { this.toggleCreateModal(false); }, showBlankState () { return !this.props.loading && !this.props.items.results.length && !this.props.active.search && !this.props.active.filters.length; }, renderBlankState () { const { currentList } = this.props; if (!this.showBlankState()) return null; // create and nav directly to the item view, or open the create modal const onClick = currentList.autocreate ? this.createAutocreate : this.openCreateModal; // display the button if create allowed const button = !currentList.nocreate ? ( <GlyphButton color="success" glyph="plus" position="left" onClick={onClick} data-e2e-list-create-button="no-results"> Create {currentList.singular} </GlyphButton> ) : null; return ( <Container> {(this.props.error) ? ( <FlashMessages messages={{ error: [{ title: "There is a problem with the network, we're trying to reconnect...", }] }} /> ) : null} <BlankState heading={`No ${this.props.currentList.plural.toLowerCase()} found...`} style={{ marginTop: 40 }}> {button} </BlankState> </Container> ); }, renderActiveState () { if (this.showBlankState()) return null; const containerStyle = { transition: 'max-width 160ms ease-out', msTransition: 'max-width 160ms ease-out', MozTransition: 'max-width 160ms ease-out', WebkitTransition: 'max-width 160ms ease-out', }; if (!this.state.constrainTableWidth) { containerStyle.maxWidth = '100%'; } return ( <div> {this.renderHeader()} <Container> <div style={{ height: 35, marginBottom: '1em', marginTop: '1em' }}> {this.renderManagement()} {this.renderPagination()} <span style={{ clear: 'both', display: 'table' }} /> </div> </Container> <Container style={containerStyle}> {(this.props.error) ? ( <FlashMessages messages={{ error: [{ title: "There is a problem with the network, we're trying to reconnect..", }] }} /> ) : null} {(this.props.loading) ? ( <Center height="50vh"> <Spinner /> </Center> ) : ( <div> <ItemsTable activeSort={this.props.active.sort} checkedItems={this.state.checkedItems} checkTableItem={this.checkTableItem} columns={this.props.active.columns} deleteTableItem={this.deleteTableItem} handleSortSelect={this.handleSortSelect} items={this.props.items} list={this.props.currentList} manageMode={this.state.manageMode} rowAlert={this.props.rowAlert} currentPage={this.props.lists.page.index} pageSize={this.props.lists.page.size} drag={this.props.lists.drag} dispatch={this.props.dispatch} /> {this.renderNoSearchResults()} </div> )} </Container> </div> ); }, renderNoSearchResults () { if (this.props.items.results.length) return null; let matching = this.props.active.search; if (this.props.active.filters.length) { matching += (matching ? ' and ' : '') + pluralize(this.props.active.filters.length, '* filter', '* filters'); } matching = matching ? ' found matching ' + matching : '.'; return ( <BlankState style={{ marginTop: 20, marginBottom: 20 }}> <Glyph name="search" size="medium" style={{ marginBottom: 20 }} /> <h2 style={{ color: 'inherit' }}> No {this.props.currentList.plural.toLowerCase()}{matching} </h2> </BlankState> ); }, render () { if (!this.props.ready) { return ( <Center height="50vh" data-screen-id="list"> <Spinner /> </Center> ); } return ( <div data-screen-id="list"> {this.renderBlankState()} {this.renderActiveState()} <CreateForm err={Keystone.createFormErrors} isOpen={this.state.showCreateForm} list={this.props.currentList} onCancel={this.closeCreateModal} onCreate={this.onCreate} /> <UpdateForm isOpen={this.state.showUpdateForm} itemIds={Object.keys(this.state.checkedItems)} list={this.props.currentList} onCancel={() => this.toggleUpdateModal(false)} /> {this.renderConfirmationDialog()} </div> ); }, }); module.exports = connect((state) => { return { lists: state.lists, loading: state.lists.loading, error: state.lists.error, currentList: state.lists.currentList, items: state.lists.items, page: state.lists.page, ready: state.lists.ready, rowAlert: state.lists.rowAlert, active: state.active, }; })(ListView);
react-router/components/Home.js
ybbkrishna/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; class Home extends React.Component { render() { return <p>Welcome to the site!</p>; } } export default Home;
src/Button.entry.js
giovanni0918/react-component-catalog
import React from 'react'; import { render } from 'react-dom'; import Button from './components/Button/Button.js'; render( <Button className='Button Button--primary' onClick={(event) => console.log('Button Button--primary')} textContent='hello' />, document.getElementById('Button') );
src/components/category/component/_category.js
chemoish/react-webpack
import React from 'react'; import Router from 'react-router'; var {Link} = Router; export default React.createClass({ render() { let category = this.props.category; return ( <Link className="category" to="category" params={{slug: category.category}}> <div className="category-image"> <img src={category.images.web.url} /> </div> <span className="category-title">{category.title}!</span> </Link> ); } });
definitions/npm/react-i18next_v2.x.x/test_react-i18next_v2.x.x.js
doberkofler/flow-typed
// @flow import React from 'react' import { loadNamespaces, translate, I18nextProvider, Interpolate, } from 'react-i18next' import type { TFunction, Translator } from 'react-i18next' const i18n = { loadNamespaces: () => {} }; <I18nextProvider i18n={ i18n } children={ <div /> } />; // $ExpectError - missing children prop <I18nextProvider i18n={ i18n } />; // $ExpectError - missing i18n prop <I18nextProvider children={ <div /> } />; // passing loadNamespaces({ components: [], i18n }); loadNamespaces({ components: [() => <div />], i18n }); // $ExpectError - too few arguments loadNamespaces(); // $ExpectError - wrong type loadNamespaces(''); // $ExpectError - wrong component type loadNamespaces({ components: [{}], i18n }); type OwnProps = { s: string }; type Props = OwnProps & { t: TFunction }; const Comp = ({ s, t }: Props) => ( <div prop1={ t('') } prop2={ ' ' + s } /> ); class ClassComp extends React.Component { props: Props; render() { const { s, t } = this.props; return <div prop={ t('') } />; } } // $ExpectError - wrong argument type const FlowErrorComp = ({ s, t }: Props) => ( <div prop1={ t('', '') } // misuse of t() prop2={ ' ' + s } /> ); class FlowErrorClassComp extends React.Component { props: Props; render() { // $ExpectError - wrong argument type const { s, t } = this.props; return <div prop={ t({}) } />; // misuse of t() } } // $ExpectError - too few arguments translate(); // $ExpectError - wrong argument type translate({}); const translator: Translator<OwnProps, Props> = translate(''); const WrappedStatelessComp = translator(Comp); // passing <WrappedStatelessComp s="" />; // $ExpectError - missing prop "s" <WrappedStatelessComp />; // $ExpectError - wrong type <WrappedStatelessComp s={ 1 } />; const WrappedClassComp = translator(ClassComp); // passing <WrappedClassComp s="" />; // $ExpectError - missing prop "s" <WrappedClassComp />; // $ExpectError - wrong type <WrappedClassComp s={ 1 } />; // passing <Interpolate />; <Interpolate children={ <div /> } className="string" />; // $ExpectError - className prop wrong type <Interpolate className={ null } />; // $ExpectError - children prop wrong type <Interpolate children={ {} } />;
src/js/Components/Chronometer.js
gabsprates/facomp-quiz
import React from 'react'; export default function Heart(props) { const iconStyle = { color: '#f11', }; const divStyle = { width: '50px', height: '50px', display: 'flex', marginLeft: 'auto', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f5f5f5' }; return ( <div> <div className='heart' style={ divStyle }> <span style={ iconStyle }> <svg width="100%" height="100%" viewBox="0 0 30 30"><path d="M8.8,23l-0.7,0.7c-0.3,0.3-0.3,0.8,0,1.1C8.2,25,8.4,25,8.6,25S9,25,9.2,24.8l0.7-0.7c0.3-0.3,0.3-0.8,0-1.1 S9.1,22.8,8.8,23z M7,17.2H6c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8h1c0.4,0,0.8-0.3,0.8-0.8S7.4,17.2,7,17.2z M15,10.6 c0.4,0,0.8-0.3,0.8-0.8v-1c0-0.4-0.3-0.8-0.8-0.8s-0.8,0.3-0.8,0.8v1C14.2,10.3,14.6,10.6,15,10.6z M9.2,11c-0.3-0.3-0.8-0.3-1.1,0 c-0.3,0.3-0.3,0.8,0,1.1l0.7,0.7C8.9,12.9,9.1,13,9.3,13s0.4-0.1,0.5-0.2c0.3-0.3,0.3-0.8,0-1.1L9.2,11z M18.5,13.3l-3.3,3.2 c-0.5-0.1-1,0-1.4,0.3c-0.6,0.6-0.6,1.5,0,2.1c0.6,0.6,1.5,0.6,2.1,0c0.4-0.4,0.5-0.9,0.4-1.4l3.3-3.2c0.3-0.3,0.3-0.8,0-1.1 C19.3,13,18.8,13,18.5,13.3z M15.8,5.9V5.3c1.1-0.3,2-1.4,2-2.6C17.7,1.3,16.5,0,15,0c-1.5,0-2.7,1.2-2.7,2.7c0,1.2,0.8,2.3,2,2.6 v0.6C8,6.3,3,11.5,3,17.8c0,6.6,5.4,12,12,12s12-5.4,12-12C27,11.5,22,6.3,15.8,5.9z M13.8,2.8c0-0.7,0.5-1.2,1.2-1.2 c0.7,0,1.2,0.5,1.2,1.2C16.2,3.4,15.7,4,15,4C14.3,4,13.8,3.4,13.8,2.8z M15,28.3c-5.8,0-10.5-4.7-10.5-10.5S9.2,7.4,15,7.4 s10.5,4.7,10.5,10.5S20.8,28.3,15,28.3z M15,25.2c-0.4,0-0.8,0.3-0.8,0.8v1c0,0.4,0.3,0.8,0.8,0.8s0.8-0.3,0.8-0.8v-1 C15.8,25.5,15.4,25.2,15,25.2z M24,17.2h-1c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8h1c0.4,0,0.8-0.3,0.8-0.8S24.4,17.2,24,17.2z M20.8,11l-0.7,0.7c-0.3,0.3-0.3,0.8,0,1.1c0.1,0.1,0.3,0.2,0.5,0.2c0.2,0,0.4-0.1,0.5-0.2l0.7-0.7c0.3-0.3,0.3-0.8,0-1.1 C21.6,10.7,21.1,10.7,20.8,11z M21.2,23c-0.3-0.3-0.8-0.3-1.1,0c-0.3,0.3-0.3,0.8,0,1.1l0.7,0.7C21,25,21.2,25,21.4,25 c0.2,0,0.4-0.1,0.5-0.2c0.3-0.3,0.3-0.8,0-1.1L21.2,23z" fill="#262324"/></svg> </span> </div> </div> ); }
src/chatbot/Animatable.js
Endore8/i-chatbot
import React from 'react' import { CSSTransition } from 'react-transition-group' const Animatable = ({ children, ...props }) => ( <CSSTransition {...props} timeout={{ enter: 500, exit: 300 }}> {children} </CSSTransition> ) export default Animatable
imports/ui/components/messenger/messageItem.js
jiyuu-llc/jiyuu
import React from 'react'; import Hammer from 'react-hammerjs'; import Render from '../../components/render.jsx' const MessageItem = ({data}) => ({ handleTap: function(data){ const dId = ("#d-" + data._id); /* const fdId = ("#fd-" + data._id); */ if(data.userId == Meteor.userId()){ $(dId).toggle(); }else{ return false; } }, deleteMsg(data){ Meteor.call('msg.delete',Session.get("convoId"),data._id); }, fakeDeleteMsg(data){ Meteor.call('msg.fakeDelete',Session.get("convoId"),data._id); }, render() { var color; if (data.userId !== Meteor.userId()){ color = "message-them"; } else { color = "message-you"; } return ( <Hammer onDoubleTap={this.handleTap.bind(this, data)}> <div id={data._id} className="message-item"> <div className={color}> <div id={"d-" + data._id} onClick={this.deleteMsg.bind(this, data)} className="message-delete"><i className="fa fa-times" aria-hidden="true"/>1</div> <div id={"fd-" + data._id} onClick={this.fakeDeleteMsg.bind(this, data)} className="message-delete"><i className="fa fa-times" aria-hidden="true"/></div> <div>{data.text}</div> <Render data={data}/> </div> </div> </Hammer> ); } }); export default MessageItem;
App.js
FuzzyHatPublishing/isleep
import React from 'react'; import { AsyncStorage, Platform, StatusBar, StyleSheet, View } from 'react-native'; import { AppLoading, Asset, Font } from 'expo'; import { Ionicons } from '@expo/vector-icons'; import RootNavigation from './navigation/RootNavigation'; import TourScreen from './screens/TourScreen'; export default class App extends React.Component { constructor() { super(); this.handler = this.handler.bind(this) this.state = { assetsAreLoaded: false, firstLaunch: null, showTour: true } } componentDidMount() { AsyncStorage.getItem("alreadyLaunched").then(value => { if(value == null) { AsyncStorage.setItem('alreadyLaunched', '1'); this.setState({firstLaunch: true}); } else { this.setState({firstLaunch: false}); }}) } componentWillMount() { this._loadAssetsAsync(); } handler(e) { this.setState({ showTour: false }) } render() { if (!this.state.assetsAreLoaded && !this.props.skipLoadingScreen || this.state.firstLaunch === null) { return <AppLoading />; } else { if(this.state.firstLaunch == true && this.state.showTour == true) { return <TourScreen handler={this.handler} />; } else { return <RootNavigation />; } } } async _loadAssetsAsync() { try { await Promise.all([ Asset.loadAsync([ require('./assets/images/robot-dev.png'), require('./assets/images/robot-prod.png'), ]), Font.loadAsync([ // This is the font that we are using for our tab bar Ionicons.font, // We include SpaceMono because we use it in HomeScreen.js. Feel free // to remove this if you are not using it in your app { 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') }, ]), ]); } catch (e) { // In this case, you might want to report the error to your error // reporting service, for example Sentry console.warn( 'There was an error caching assets (see: App.js), perhaps due to a ' + 'network timeout, so we skipped caching. Reload the app to try again.' ); console.log(e); } finally { this.setState({ assetsAreLoaded: true }); } } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, statusBarUnderlay: { height: 24, backgroundColor: 'rgba(0,0,0,0.2)', }, });
demo/src/Loading.js
tkh44/data-driven-motion
import React from 'react' export default function Loading ({isLoading, error, pastDelay}) { if (isLoading) { return pastDelay ? <div>Loading...</div> : null // Don't flash "Loading..." when we don't need to. } else if (error) { return ( <pre> <h1>Error</h1> {JSON.stringify(error, null, 2)} </pre> ) } else { return null } }
src/modules/users/components/BookshelfList/BookshelfList.js
cltk/cltk_frontend
import React from 'react'; import Masonry from 'react-masonry-component/lib'; import PropTypes from 'prop-types'; class BookshelfList extends React.Component { render() { const masonryOptions = { isFitWidth: true, transitionDuration: 300, }; return ( <div className="works-list works-list--bookshelf"> {this.props.works && this.props.works.length ? <Masonry options={masonryOptions} className="works-container works-container--grid row" > {this.props.works.map((work, i) => ( <WorkTeaser key={i} work={work} /> ))} </Masonry> : <div> <p className="no-results no-results--bookshelf"> You do not have any works saved on your bookshelf yet. <a href="/browse">Add one by browsing the corpora.</a> </p> </div> } </div> ); } }; BookshelfList.propTypes = { works: PropTypes.array, }; export default BookshelfList;
frontend/src/Calendar/Events/CalendarEvent.js
lidarr/Lidarr
import classNames from 'classnames'; import moment from 'moment'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import getStatusStyle from 'Calendar/getStatusStyle'; import Icon from 'Components/Icon'; import Link from 'Components/Link/Link'; import { icons } from 'Helpers/Props'; import CalendarEventQueueDetails from './CalendarEventQueueDetails'; import styles from './CalendarEvent.css'; class CalendarEvent extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isDetailsModalOpen: false }; } // // Listeners onPress = () => { this.setState({ isDetailsModalOpen: true }, () => { this.props.onEventModalOpenToggle(true); }); } onDetailsModalClose = () => { this.setState({ isDetailsModalOpen: false }, () => { this.props.onEventModalOpenToggle(false); }); } // // Render render() { const { id, artist, title, foreignAlbumId, releaseDate, monitored, statistics, grabbed, queueItem, // timeFormat, colorImpairedMode } = this.props; if (!artist) { return null; } const startTime = moment(releaseDate); // const endTime = startTime.add(artist.runtime, 'minutes'); const downloading = !!(queueItem || grabbed); const isMonitored = artist.monitored && monitored; const statusStyle = getStatusStyle(id, downloading, startTime, isMonitored, statistics.percentOfTracks); return ( <div> <Link className={classNames( styles.event, styles[statusStyle], colorImpairedMode && 'colorImpaired' )} component="div" onPress={this.onPress} > <div className={styles.info}> <div className={styles.artistName}> <Link to={`/artist/${artist.foreignArtistId}`}> {artist.artistName} </Link> </div> { !!queueItem && <span className={styles.statusIcon}> <CalendarEventQueueDetails {...queueItem} /> </span> } { !queueItem && grabbed && <Icon className={styles.statusIcon} name={icons.DOWNLOADING} title="Album is downloading" /> } </div> <div className={styles.albumInfo}> <div className={styles.albumTitle}> <Link to={`/album/${foreignAlbumId}`}> {title} </Link> </div> </div> </Link> </div> ); } } CalendarEvent.propTypes = { id: PropTypes.number.isRequired, artist: PropTypes.object.isRequired, title: PropTypes.string.isRequired, foreignAlbumId: PropTypes.string.isRequired, statistics: PropTypes.object.isRequired, releaseDate: PropTypes.string.isRequired, monitored: PropTypes.bool.isRequired, grabbed: PropTypes.bool, queueItem: PropTypes.object, // timeFormat: PropTypes.string.isRequired, colorImpairedMode: PropTypes.bool.isRequired, onEventModalOpenToggle: PropTypes.func.isRequired }; CalendarEvent.defaultProps = { statistics: { percentOfTracks: 0 } }; export default CalendarEvent;
src/svg-icons/image/straighten.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageStraighten = (props) => ( <SvgIcon {...props}> <path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z"/> </SvgIcon> ); ImageStraighten = pure(ImageStraighten); ImageStraighten.displayName = 'ImageStraighten'; ImageStraighten.muiName = 'SvgIcon'; export default ImageStraighten;
src/components/CardModal.js
robshox/boostv1
import React from 'react'; import ReactDOM from 'react-dom'; import { Link, browserHistory } from 'react-router'; const CardModal = React.createClass({ componentDidUpdate() { ReactDOM.findDOMNode(this.refs.front).focus(); }, render() { let { card, onDelete } = this.props; return (<div className='modal'> <h1> { onDelete ? 'Edit' : 'New' } Card </h1> <label> Card Front: </label> <textarea ref='front' defaultValue={card.front}></textarea> <label> Card Back: </label> <textarea ref='back' defaultValue={card.back}></textarea> <p> <button onClick={this.onSave}> Save Card </button> <Link className='btn' to={`/deck/${card.deckId}`}> Cancel </Link> { onDelete ? <button onClick={this.onDelete} className='delete'> Delete Card </button> : null} </p> </div>); }, onSave(evt) { var front = ReactDOM.findDOMNode(this.refs.front); var back = ReactDOM.findDOMNode(this.refs.back); this.props.onSave(Object.assign({}, this.props.card, { front: front.value, back: back.value })); browserHistory.push(`/deck/${this.props.card.deckId}`); }, onDelete(e) { this.props.onDelete(this.props.card.id); browserHistory.push(`/deck/${this.props.card.deckId}`); } }); export default CardModal;
app/js/pages/loadingPage.js
Dennetix/Motwo
import React from 'react'; import theme from '../utils/theme'; @theme export default class LoginPage extends React.Component { getStyle() { return { container: { width: '100%', height: '100vh' }, loader: { width: '75px', height: '75px', position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -60%)' } }; } render() { let style = this.getStyle(); return ( <div style={style.container}> <img style={style.loader} src={this.props.getThemeProp('animationLoader', true)}/> </div> ); } }
src/decorators/withViewport.js
zhangmhao/circle
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
webpack/scenes/AnsibleCollections/AnsibleCollectionsTableSchema.js
snagoor/katello
import React from 'react'; import { Link } from 'react-router-dom'; import { translate as __ } from 'foremanReact/common/I18n'; import { urlBuilder } from 'foremanReact/common/urlHelpers'; import { headerFormatter, cellFormatter, } from '../../components/pf3Table/formatters'; const TableSchema = [ { property: 'name', header: { label: __('Name'), formatters: [headerFormatter], }, cell: { formatters: [ (value, { rowData }) => ( <td> <Link to={urlBuilder('legacy_ansible_collections', '', rowData.id)}>{rowData.name}</Link> </td> ), ], }, }, { property: 'namespace', header: { label: __('Author'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, { property: 'version', header: { label: __('Version'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, { property: 'checksum', header: { label: __('Checksum'), formatters: [headerFormatter], }, cell: { formatters: [cellFormatter], }, }, ]; export default TableSchema;
reaction/src/App.js
onespeed-workshops/the-vue-reaction
import React, { Component } from 'react'; import { TodoForm } from './TodoForm' import { TodoList } from './TodoList' class Root extends Component { constructor(props) { super(props) this.state = { localTodo: { value: '' }, todos: [] } } onLocalUpdate(newTodo) { this.setState({ ...this.state, localTodo: { ...newTodo } }) } onSubmit(newTodo) { const currentTodos = this.state.todos const id = currentTodos.length; const newState = { ...this.state, localTodo: { value: '' }, todos: [ ...currentTodos, { id, ...newTodo } ] } this.setState(newState) } onDelete(id) { const todos = this.state.todos.filter((todo) => todo.id !== id) this.setState({ ...this.state, todos }) } render() { return ( <div className="todo-app"> <h1>REACT</h1> <TodoForm localTodo={this.state.localTodo} onSubmit={this.onSubmit.bind(this)} onLocalUpdate={this.onLocalUpdate.bind(this)} /> <TodoList todos={this.state.todos} onDelete={this.onDelete.bind(this)} /> </div> ); } } export default Root
src/streamlist/StreamList.js
saketkumar95/zulip-mobile
/* @flow */ import React from 'react'; import { FlatList, StyleSheet } from 'react-native'; import StreamItem from './StreamItem'; const styles = StyleSheet.create({ list: { flex: 1, flexDirection: 'column', }, }); export default class StreamList extends React.Component { props: { streams: Object[], selected?: boolean, showDescriptions: boolean, showSwitch: boolean, onNarrow: (streamName: string) => void, onSwitch: (streamName: string, newValue: boolean) => void, }; static defaultProps: { showSwitch: false, showDescriptions: false, onSwitch: (streamName: string, newValue: boolean) => void, selected: false, }; render() { const { streams, selected, showDescriptions, showSwitch, onNarrow, onSwitch } = this.props; const sortedStreams = streams.sort((a, b) => a.name.localeCompare(b.name)); return ( <FlatList style={styles.list} initialNumToRender={sortedStreams.length} data={sortedStreams} keyExtractor={item => item.stream_id} renderItem={({ item }) => ( <StreamItem name={item.name} iconSize={16} isPrivate={item.invite_only} description={(showDescriptions) ? item.description : ''} color={item.color} isSelected={item.name === selected} isMuted={item.in_home_view === false} // if 'undefined' is not muted showSwitch={showSwitch} isSwitchedOn={item.subscribed} onPress={onNarrow} onSwitch={onSwitch} /> )} /> ); } }
packages/material-ui-icons/legacy/SignalWifi1BarLock.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3" /><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z" /></React.Fragment> , 'SignalWifi1BarLock');
src/components/options/OptionsImage3x.js
m0sk1t/react_email_editor
import React from 'react'; const OptionsImage3x = ({ block, language, onFileChange, onPropChange }) => { return ( <div> <div> <label>{language["Custom style"]}: <input type="checkbox" checked={block.options.container.customStyle? 'checked': '' } onChange={(e) => onPropChange('customStyle', !block.options.container.customStyle, true)} /></label> </div> <div> <label> {language["URL"]} 1: <label> <input type="file" onChange={(e) => { onFileChange(block, 0, e.target.files[0]); }} /> <div>&#8853;</div> </label> <input type="text" value={block.options.elements[0].source} onChange={(e) => onPropChange('source', e.target.value, false, 0)} /> </label> </div> <div> <label>{language["Link"]} 1: <input type="text" value={block.options.elements[0].link} onChange={(e) => onPropChange('link', e.target.value, false, 0)} /></label> </div> <hr /> <div> <label> {language["URL"]} 2: <label> <input type="file" onChange={(e) => { onFileChange(block, 1, e.target.files[0]); }} /> <div>&#8853;</div> </label> <input type="text" value={block.options.elements[1].source} onChange={(e) => onPropChange('source', e.target.value, false, 1)} /> </label> </div> <div> <label>{language["Link"]} 2: <input type="text" value={block.options.elements[1].link} onChange={(e) => onPropChange('link', e.target.value, false, 1)} /></label> </div> <hr /> <div> <label> {language["URL"]} 3: <label> <input type="file" onChange={(e) => { onFileChange(block, 2, e.target.files[0]); }} /> <div>&#8853;</div> </label> <input type="text" value={block.options.elements[2].source} onChange={(e) => onPropChange('source', e.target.value, false, 2)} /> </label> </div> <div> <label>{language["Link"]} 3: <input type="text" value={block.options.elements[2].link} onChange={(e) => onPropChange('link', e.target.value, false, 2)} /></label> </div> <div> <label>{language["Add paddings"]}: <input type="checkbox" checked={block.options.container.usePadding? 'checked': ''} onChange={(e) => onPropChange('usePadding', !block.options.container.usePadding, true)} /></label> </div> <div> <label>{language["Border radius"]}: <input type="text" value={block.options.elements[0].borderRadius} onChange={(e) => onPropChange('borderRadius', e.target.value, false, 0)} /></label> </div> <hr /> <div> <label>{language["Background"]}: <input type="color" value={block.options.container.backgroundColor} onChange={(e) => onPropChange('backgroundColor', e.target.value, true)} /></label> </div> </div> ); }; export default OptionsImage3x;
src/components/utils/Gutters.js
jckfa/img.silly.graphics
import React from 'react' import styled from 'styled-components' import media from './media' import { spacing } from '../config/vars' const Container = styled.div` padding-left: ${spacing.gutter}em; padding-right: ${spacing.gutter}em; ${media.s` padding-left: ${spacing.gutter * 2}em; padding-right: ${spacing.gutter * 2}em; `} ` const Gutters = (props) => ( <Container> {props.children} </Container> ) export default Gutters
packages/wix-style-react/src/MultiSelect/test/MultiSelect.e2eStory.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { getTestStoryKind } from '../../../stories/storiesHierarchy'; import { storySettings, testStories } from './storySettings'; import { RTLWrapper } from '../../../stories/utils/RTLWrapper'; import MultiSelect from '..'; import ExampleReorderable from './Reorderable'; import TestTabsSwitches from './TestTabsSwitches'; import StateSelection from './StateSelection'; const kind = getTestStoryKind({ category: storySettings.category, storyName: storySettings.storyName, }); const MultiSelectTests = storiesOf(kind, module); MultiSelectTests.add(testStories.withMaxNumRows, () => ( <RTLWrapper> <div style={{ width: '400px' }}> numOfRows=2: <MultiSelect dataHook="multi-select-limited" tags={[ { id: '1', label: 'aaaaaaaaaaaa' }, { id: '2', label: 'aaaaaaaaaaaa' }, { id: '3', label: 'aaaaaaaaaaaa' }, { id: '4', label: 'aaaaaaaaaaaa' }, { id: '5', label: 'aaaaaaaaaaaa' }, { id: '6', label: 'aaaaaaaaaaaa' }, ]} maxNumRows={2} /> </div> </RTLWrapper> )); MultiSelectTests.add(testStories.reorderable, () => ( <RTLWrapper> <ExampleReorderable /> </RTLWrapper> )); MultiSelectTests.add(testStories.tabsSwitches, () => ( <div> <input data-hook="input-for-focus-1" /> <TestTabsSwitches /> <input data-hook="input-for-focus-2" /> </div> )); MultiSelectTests.add(testStories.stateMultiSelect, () => ( <StateSelection dataHook={storySettings.dataHook} /> ));
src/components/Navbar/Tabs.js
nicolas-adamini/littleblue
import React from 'react'; import { withRouter } from 'react-router-dom'; const Tabs = props => { const handleClick = e => { props.history.push('/' + e.target.name); } const pathname = props.location.pathname; return ( <div className="tabs"> <button name="web" onClick={handleClick} className={pathname === '/' || pathname === '/web' ? 'active' : ''} > Web </button> <button name="images" onClick={handleClick} className={pathname === '/images' ? 'active' : ''} > Images </button> <button name="videos" onClick={handleClick} className={pathname === '/videos' ? 'active' : ''} > Videos </button> <button name="maps" onClick={handleClick} className={pathname === '/maps' ? 'active' : ''} > Maps </button> </div> ); } export default withRouter(Tabs);
examples/ChartsExplorer/components/Pie.js
Jpadilla1/react-native-ios-charts
import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { PieChart } from 'react-native-ios-charts'; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: 'transparent' } }); export default class Pie extends Component { static displayName = 'Pie'; render() { const config = { dataSets: [{ values: [0.14, 0.14, 0.34, 0.38], colors: ['rgb(197, 255, 140)', 'rgb(255, 247, 140)', 'rgb(255, 210, 141)', 'rgb(140, 235, 255)'], label: 'Quarter Revenues 2014' }], labels: ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'], centerText: 'Quartely Revenue', legend: { position: 'aboveChartRight', wordWrap: true }, valueFormatter: { type: 'regular', numberStyle: 'PercentStyle', maximumDecimalPlaces: 0 } }; return ( <PieChart config={config} style={styles.container}/> ); } }
client/app/scripts/charts/nodes-chart.js
dilgerma/scope
import _ from 'lodash'; import d3 from 'd3'; import debug from 'debug'; import React from 'react'; import { connect } from 'react-redux'; import { Map as makeMap, fromJS, is as isDeepEqual } from 'immutable'; import timely from 'timely'; import { clickBackground } from '../actions/app-actions'; import { EDGE_ID_SEPARATOR } from '../constants/naming'; import { DETAILS_PANEL_WIDTH } from '../constants/styles'; import Logo from '../components/logo'; import { doLayout } from './nodes-layout'; import NodesChartElements from './nodes-chart-elements'; import { getActiveTopologyOptions, getAdjacentNodes, isSameTopology } from '../utils/topology-utils'; const log = debug('scope:nodes-chart'); const MARGINS = { top: 130, left: 40, right: 40, bottom: 0 }; const ZOOM_CACHE_FIELDS = ['scale', 'panTranslateX', 'panTranslateY']; // make sure circular layouts a bit denser with 3-6 nodes const radiusDensity = d3.scale.threshold() .domain([3, 6]).range([2.5, 3.5, 3]); class NodesChart extends React.Component { constructor(props, context) { super(props, context); this.handleMouseClick = this.handleMouseClick.bind(this); this.zoomed = this.zoomed.bind(this); this.state = { edges: makeMap(), nodes: makeMap(), nodeScale: d3.scale.linear(), panTranslateX: 0, panTranslateY: 0, scale: 1, selectedNodeScale: d3.scale.linear(), hasZoomed: false, height: 0, width: 0, zoomCache: {} }; } componentWillMount() { const state = this.updateGraphState(this.props, this.state); this.setState(state); } componentWillReceiveProps(nextProps) { // gather state, setState should be called only once here const state = _.assign({}, this.state); // wipe node states when showing different topology if (nextProps.topologyId !== this.props.topologyId) { // re-apply cached canvas zoom/pan to d3 behavior (or set defaul values) const defaultZoom = { scale: 1, panTranslateX: 0, panTranslateY: 0, hasZoomed: false }; const nextZoom = this.state.zoomCache[nextProps.topologyId] || defaultZoom; if (nextZoom) { this.zoom.scale(nextZoom.scale); this.zoom.translate([nextZoom.panTranslateX, nextZoom.panTranslateY]); } // saving previous zoom state const prevZoom = _.pick(this.state, ZOOM_CACHE_FIELDS); const zoomCache = _.assign({}, this.state.zoomCache); zoomCache[this.props.topologyId] = prevZoom; // clear canvas and apply zoom state _.assign(state, nextZoom, { zoomCache }, { nodes: makeMap(), edges: makeMap() }); } // reset layout dimensions only when forced state.height = nextProps.forceRelayout ? nextProps.height : (state.height || nextProps.height); state.width = nextProps.forceRelayout ? nextProps.width : (state.width || nextProps.width); // _.assign(state, this.updateGraphState(nextProps, state)); if (nextProps.forceRelayout || !isSameTopology(nextProps.nodes, this.props.nodes)) { _.assign(state, this.updateGraphState(nextProps, state)); } if (this.props.selectedNodeId !== nextProps.selectedNodeId) { _.assign(state, this.restoreLayout(state)); } if (nextProps.selectedNodeId) { _.assign(state, this.centerSelectedNode(nextProps, state)); } this.setState(state); } componentDidMount() { // distinguish pan/zoom from click this.isZooming = false; this.zoom = d3.behavior.zoom() .scaleExtent([0.1, 2]) .on('zoom', this.zoomed); d3.select('.nodes-chart svg') .call(this.zoom); } componentWillUnmount() { // undoing .call(zoom) d3.select('.nodes-chart svg') .on('mousedown.zoom', null) .on('onwheel', null) .on('onmousewheel', null) .on('dblclick.zoom', null) .on('touchstart.zoom', null); } render() { const { edges, nodes, panTranslateX, panTranslateY, scale } = this.state; // not passing translates into child components for perf reasons, use getTranslate instead const translate = [panTranslateX, panTranslateY]; const transform = `translate(${translate}) scale(${scale})`; const svgClassNames = this.props.isEmpty ? 'hide' : ''; return ( <div className="nodes-chart"> <svg width="100%" height="100%" id="nodes-chart-canvas" className={svgClassNames} onClick={this.handleMouseClick}> <g transform="translate(24,24) scale(0.25)"> <Logo /> </g> <NodesChartElements layoutNodes={nodes} layoutEdges={edges} nodeScale={this.state.nodeScale} scale={scale} transform={transform} selectedNodeScale={this.state.selectedNodeScale} layoutPrecision={this.props.layoutPrecision} /> </svg> </div> ); } handleMouseClick() { if (!this.isZooming) { this.props.clickBackground(); } else { this.isZooming = false; } } initNodes(topology, stateNodes) { let nextStateNodes = stateNodes; // remove nodes that have disappeared stateNodes.forEach((node, id) => { if (!topology.has(id)) { nextStateNodes = nextStateNodes.delete(id); } }); // copy relevant fields to state nodes topology.forEach((node, id) => { nextStateNodes = nextStateNodes.mergeIn([id], makeMap({ id, label: node.get('label'), pseudo: node.get('pseudo'), subLabel: node.get('label_minor'), nodeCount: node.get('node_count'), metrics: node.get('metrics'), rank: node.get('rank'), shape: node.get('shape'), stack: node.get('stack') })); }); return nextStateNodes; } initEdges(topology, stateNodes) { let edges = makeMap(); topology.forEach((node, nodeId) => { const adjacency = node.get('adjacency'); if (adjacency) { adjacency.forEach(adjacent => { const edge = [nodeId, adjacent]; const edgeId = edge.join(EDGE_ID_SEPARATOR); if (!edges.has(edgeId)) { const source = edge[0]; const target = edge[1]; if (stateNodes.has(source) && stateNodes.has(target)) { edges = edges.set(edgeId, makeMap({ id: edgeId, value: 1, source, target })); } } }); } }); return edges; } centerSelectedNode(props, state) { let stateNodes = state.nodes; let stateEdges = state.edges; const selectedLayoutNode = stateNodes.get(props.selectedNodeId); if (!selectedLayoutNode) { return {}; } const adjacentNodes = props.adjacentNodes; const adjacentLayoutNodeIds = []; adjacentNodes.forEach(adjacentId => { // filter loopback if (adjacentId !== props.selectedNodeId) { adjacentLayoutNodeIds.push(adjacentId); } }); // move origin node to center of viewport const zoomScale = state.scale; const translate = [state.panTranslateX, state.panTranslateY]; const centerX = (-translate[0] + (state.width + MARGINS.left - DETAILS_PANEL_WIDTH) / 2) / zoomScale; const centerY = (-translate[1] + (state.height + MARGINS.top) / 2) / zoomScale; stateNodes = stateNodes.mergeIn([props.selectedNodeId], { x: centerX, y: centerY }); // circle layout for adjacent nodes const adjacentCount = adjacentLayoutNodeIds.length; const density = radiusDensity(adjacentCount); const radius = Math.min(state.width, state.height) / density / zoomScale; const offsetAngle = Math.PI / 4; stateNodes = stateNodes.map((node) => { const index = adjacentLayoutNodeIds.indexOf(node.get('id')); if (index > -1) { const angle = offsetAngle + Math.PI * 2 * index / adjacentCount; return node.merge({ x: centerX + radius * Math.sin(angle), y: centerY + radius * Math.cos(angle) }); } return node; }); // fix all edges for circular nodes stateEdges = stateEdges.map(edge => { if (edge.get('source') === selectedLayoutNode.get('id') || edge.get('target') === selectedLayoutNode.get('id') || _.includes(adjacentLayoutNodeIds, edge.get('source')) || _.includes(adjacentLayoutNodeIds, edge.get('target'))) { const source = stateNodes.get(edge.get('source')); const target = stateNodes.get(edge.get('target')); return edge.set('points', fromJS([ {x: source.get('x'), y: source.get('y')}, {x: target.get('x'), y: target.get('y')} ])); } return edge; }); // auto-scale node size for selected nodes const selectedNodeScale = this.getNodeScale(adjacentNodes, state.width, state.height); return { selectedNodeScale, edges: stateEdges, nodes: stateNodes }; } restoreLayout(state) { // undo any pan/zooming that might have happened this.zoom.scale(state.scale); this.zoom.translate([state.panTranslateX, state.panTranslateY]); const nodes = state.nodes.map(node => node.merge({ x: node.get('px'), y: node.get('py') })); const edges = state.edges.map(edge => { if (edge.has('ppoints')) { return edge.set('points', edge.get('ppoints')); } return edge; }); return { edges, nodes }; } updateGraphState(props, state) { const n = props.nodes.size; if (n === 0) { return { nodes: makeMap(), edges: makeMap() }; } const stateNodes = this.initNodes(props.nodes, state.nodes); const stateEdges = this.initEdges(props.nodes, stateNodes); const nodeScale = this.getNodeScale(props.nodes, state.width, state.height); const nextState = { nodeScale }; const options = { width: state.width, height: state.height, scale: nodeScale, margins: MARGINS, forceRelayout: props.forceRelayout, topologyId: this.props.topologyId, topologyOptions: this.props.topologyOptions }; const timedLayouter = timely(doLayout); const graph = timedLayouter(stateNodes, stateEdges, options); log(`graph layout took ${timedLayouter.time}ms`); // extract coords and save for restore const graphNodes = graph.nodes.map(node => makeMap({ x: node.get('x'), px: node.get('x'), y: node.get('y'), py: node.get('y') })); const layoutNodes = stateNodes.mergeDeep(graphNodes); const layoutEdges = graph.edges .map(edge => edge.set('ppoints', edge.get('points'))); // adjust layout based on viewport const xFactor = (state.width - MARGINS.left - MARGINS.right) / graph.width; const yFactor = state.height / graph.height; const zoomFactor = Math.min(xFactor, yFactor); let zoomScale = this.state.scale; if (!state.hasZoomed && zoomFactor > 0 && zoomFactor < 1) { zoomScale = zoomFactor; // saving in d3's behavior cache this.zoom.scale(zoomFactor); } nextState.scale = zoomScale; if (!isDeepEqual(layoutNodes, state.nodes)) { nextState.nodes = layoutNodes; } if (!isDeepEqual(layoutEdges, state.edges)) { nextState.edges = layoutEdges; } return nextState; } getNodeScale(nodes, width, height) { const expanse = Math.min(height, width); const nodeSize = expanse / 3; // single node should fill a third of the screen const maxNodeSize = expanse / 10; const normalizedNodeSize = Math.min(nodeSize / Math.sqrt(nodes.size), maxNodeSize); return this.state.nodeScale.copy().range([0, normalizedNodeSize]); } zoomed() { // debug('zoomed', d3.event.scale, d3.event.translate); this.isZooming = true; // dont pan while node is selected if (!this.props.selectedNodeId) { this.setState({ hasZoomed: true, panTranslateX: d3.event.translate[0], panTranslateY: d3.event.translate[1], scale: d3.event.scale }); } } } function mapStateToProps(state) { return { adjacentNodes: getAdjacentNodes(state), forceRelayout: state.get('forceRelayout'), nodes: state.get('nodes').filter(node => !node.get('filtered')), selectedNodeId: state.get('selectedNodeId'), topologyId: state.get('currentTopologyId'), topologyOptions: getActiveTopologyOptions(state) }; } export default connect( mapStateToProps, { clickBackground } )(NodesChart);
src/svg-icons/image/filter-6.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter6 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V7h4V5h-4c-1.1 0-2 .89-2 2v6c0 1.11.9 2 2 2zm0-4h2v2h-2v-2z"/> </SvgIcon> ); ImageFilter6 = pure(ImageFilter6); ImageFilter6.displayName = 'ImageFilter6'; ImageFilter6.muiName = 'SvgIcon'; export default ImageFilter6;
node_modules/react-bootstrap/es/Table.js
hsavit1/gosofi_webpage
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { striped: PropTypes.bool, bordered: PropTypes.bool, condensed: PropTypes.bool, hover: PropTypes.bool, responsive: PropTypes.bool }; var defaultProps = { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; var Table = function (_React$Component) { _inherits(Table, _React$Component); function Table() { _classCallCheck(this, Table); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Table.prototype.render = function render() { var _extends2; var _props = this.props, striped = _props.striped, bordered = _props.bordered, condensed = _props.condensed, hover = _props.hover, responsive = _props.responsive, className = _props.className, props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'striped')] = striped, _extends2[prefix(bsProps, 'bordered')] = bordered, _extends2[prefix(bsProps, 'condensed')] = condensed, _extends2[prefix(bsProps, 'hover')] = hover, _extends2)); var table = React.createElement('table', _extends({}, elementProps, { className: classNames(className, classes) })); if (responsive) { return React.createElement( 'div', { className: prefix(bsProps, 'responsive') }, table ); } return table; }; return Table; }(React.Component); Table.propTypes = propTypes; Table.defaultProps = defaultProps; export default bsClass('table', Table);
src/mixins/helpers.js
robcolburn/react-slick
'use strict'; import React from 'react'; import ReactTransitionEvents from 'react/lib/ReactTransitionEvents'; import {getTrackCSS, getTrackLeft, getTrackAnimateCSS} from './trackHelper'; import assign from 'object-assign'; var helpers = { initialize: function (props) { var slideCount = React.Children.count(props.children); var listWidth = this.getWidth(this.refs.list.getDOMNode()); var trackWidth = this.getWidth(this.refs.track.getDOMNode()); var slideWidth = this.getWidth(this.getDOMNode())/props.slidesToShow; var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, currentSlide: currentSlide }, function () { var targetLeft = getTrackLeft(assign({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state)); this.setState({trackStyle: trackStyle}); this.autoPlay(); // once we're set up, trigger the initial autoplay. }); }, update: function (props) { // This method has mostly same code as initialize method. // Refactor it var slideCount = React.Children.count(props.children); var listWidth = this.getWidth(this.refs.list.getDOMNode()); var trackWidth = this.getWidth(this.refs.track.getDOMNode()); var slideWidth = this.getWidth(this.getDOMNode())/props.slidesToShow; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth }, function () { var targetLeft = getTrackLeft(assign({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state)); this.setState({trackStyle: trackStyle}); }); }, getWidth: function getWidth(elem) { return elem.getBoundingClientRect().width || elem.offsetWidth; }, adaptHeight: function () { if (this.props.adaptiveHeight) { var selector = '[data-index="' + this.state.currentSlide +'"]'; if (this.refs.list) { var slickList = this.refs.list.getDOMNode(); slickList.style.height = slickList.querySelector(selector).offsetHeight + 'px'; } } }, slideHandler: function (index) { // Functionality of animateSlide and postSlide is merged into this function // console.log('slideHandler', index); var targetSlide, currentSlide; var targetLeft, currentLeft; var callback; if (this.state.animating === true || this.state.currentSlide === index) { return; } if (this.props.fade) { currentSlide = this.state.currentSlide; // Shifting targetSlide back into the range if (index < 0) { targetSlide = index + this.state.slideCount; } else if (index >= this.state.slideCount) { targetSlide = index - this.state.slideCount; } else { targetSlide = index; } if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide) }); } callback = () => { this.setState({ animating: false }); if (this.props.afterChange) { this.props.afterChange(currentSlide); } ReactTransitionEvents.removeEndEventListener(this.refs.track.getDOMNode().children[currentSlide], callback); }; this.setState({ animating: true, currentSlide: targetSlide }, function () { ReactTransitionEvents.addEndEventListener(this.refs.track.getDOMNode().children[currentSlide], callback); }); if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, currentSlide); } this.autoPlay(); return; } targetSlide = index; if (targetSlide < 0) { if(this.props.infinite === false) { currentSlide = 0; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll); } else { currentSlide = this.state.slideCount + targetSlide; } } else if (targetSlide >= this.state.slideCount) { if(this.props.infinite === false) { currentSlide = this.state.slideCount - this.props.slidesToShow; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = 0; } else { currentSlide = targetSlide - this.state.slideCount; } } else { currentSlide = targetSlide; } targetLeft = getTrackLeft(assign({ slideIndex: targetSlide, trackRef: this.refs.track }, this.props, this.state)); currentLeft = getTrackLeft(assign({ slideIndex: currentSlide, trackRef: this.refs.track }, this.props, this.state)); if (this.props.infinite === false) { targetLeft = currentLeft; } if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, currentSlide); } if (this.props.lazyLoad) { var loaded = true; var slidesToLoad = []; for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++ ) { loaded = loaded && (this.state.lazyLoadedList.indexOf(i) >= 0); if (!loaded) { slidesToLoad.push(i); } } if (!loaded) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad) }); } } // Slide Transition happens here. // animated transition happens to target Slide and // non - animated transition happens to current Slide // If CSS transitions are false, directly go the current slide. if (this.props.useCSS === false) { this.setState({ currentSlide: currentSlide, trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state)) }, function () { if (this.props.afterChange) { this.props.afterChange(currentSlide); } }); } else { var nextStateChanges = { animating: false, currentSlide: currentSlide, trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state)), swipeLeft: null }; callback = () => { this.setState(nextStateChanges); if (this.props.afterChange) { this.props.afterChange(currentSlide); } ReactTransitionEvents.removeEndEventListener(this.refs.track.getDOMNode(), callback); }; this.setState({ animating: true, currentSlide: targetSlide, trackStyle: getTrackAnimateCSS(assign({left: targetLeft}, this.props, this.state)) }, function () { ReactTransitionEvents.addEndEventListener(this.refs.track.getDOMNode(), callback); }); } this.autoPlay(); }, swipeDirection: function (touchObject) { var xDist, yDist, r, swipeAngle; xDist = touchObject.startX - touchObject.curX; yDist = touchObject.startY - touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0) || (swipeAngle <= 360) && (swipeAngle >= 315)) { return (this.props.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (this.props.rtl === false ? 'right' : 'left'); } return 'vertical'; }, autoPlay: function () { var play = () => { if (this.state.mounted) { this.slideHandler(this.state.currentSlide + this.props.slidesToScroll); } }; if (this.props.autoplay) { window.clearTimeout(this.state.autoPlayTimer); this.setState({ autoPlayTimer: window.setTimeout(play, this.props.autoplaySpeed) }); } } }; export default helpers;
demo/examples/complex-transition/index.js
JulienPradet/react-flip
import React, { Component } from 'react'; import withRouter from 'react-router/withRouter'; import './index.scss'; import cards from './cards'; import CardList from './CardList'; class ComplexTransition extends Component { constructor(props) { super(); this.state = { cards: cards(props.match.path) }; } render() { return ( <div className="complex-container"> <CardList cards={this.state.cards} /> </div> ); } } export default withRouter(ComplexTransition);