path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
app/react-icons/fa/calendar.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaCalendar extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m4.4 37.1h6.4v-6.4h-6.4v6.4z m7.8 0h7.2v-6.4h-7.2v6.4z m-7.8-7.8h6.4v-7.2h-6.4v7.2z m7.8 0h7.2v-7.2h-7.2v7.2z m-7.8-8.6h6.4v-6.4h-6.4v6.4z m16.4 16.4h7.1v-6.4h-7.1v6.4z m-8.6-16.4h7.2v-6.4h-7.2v6.4z m17.2 16.4h6.4v-6.4h-6.4v6.4z m-8.6-7.8h7.1v-7.2h-7.1v7.2z m-7.9-19.3v-6.4q0-0.3-0.2-0.5t-0.5-0.2h-1.4q-0.3 0-0.5 0.2t-0.2 0.5v6.4q0 0.3 0.2 0.5t0.5 0.2h1.4q0.3 0 0.5-0.2t0.2-0.5z m16.5 19.3h6.4v-7.2h-6.4v7.2z m-8.6-8.6h7.1v-6.4h-7.1v6.4z m8.6 0h6.4v-6.4h-6.4v6.4z m0.7-10.7v-6.4q0-0.3-0.2-0.5t-0.5-0.2h-1.5q-0.3 0-0.5 0.2t-0.2 0.5v6.4q0 0.3 0.2 0.5t0.5 0.2h1.5q0.2 0 0.5-0.2t0.2-0.5z m8.5-1.4v28.5q0 1.2-0.8 2.1t-2 0.8h-31.4q-1.2 0-2.1-0.9t-0.8-2v-28.5q0-1.2 0.8-2t2.1-0.9h2.8v-2.1q0-1.5 1.1-2.6t2.5-1h1.4q1.5 0 2.5 1.1t1.1 2.5v2.1h8.6v-2.1q0-1.5 1-2.6t2.5-1h1.5q1.4 0 2.5 1.1t1 2.5v2.1h2.9q1.1 0 2 0.9t0.8 2z"/></g> </IconBase> ); } }
app/assets/javascripts/src/components/sharedComponents/InputErrorMessage.js
talum/creamery
import React from 'react' const InputErrorMessage = (props) => { if (props.isVisible) { return ( <div className="module"> <div className="heading heading--color-pink"> { props.message} </div> </div> ) } else { return (<div></div>) } } export default InputErrorMessage
website-prototyping-tools/RelayPlayground.js
gabelevi/relay
/** * Copyright (c) 2013-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. */ /* eslint-disable no-unused-vars, no-eval */ import './RelayPlayground.css'; import 'codemirror/mode/javascript/javascript'; import Codemirror from 'react-codemirror'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; window.Relay = Relay; import RelayLocalSchema from 'relay-local-schema'; import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin'; import debounce from 'lodash.debounce'; import defer from 'lodash.defer'; import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher'; import errorCatcherPlugin from 'babel-plugin-react-error-catcher'; import evalSchema from './evalSchema'; import getBabelRelayPlugin from 'babel-relay-plugin'; import {transform} from 'babel-core'; import {introspectionQuery} from 'graphql/utilities'; import {graphql} from 'graphql'; const {PropTypes} = React; const CODE_EDITOR_OPTIONS = { extraKeys: { Tab(cm) { // Insert spaces when the tab key is pressed const spaces = Array(cm.getOption('indentUnit') + 1).join(' '); cm.replaceSelection(spaces); }, }, indentWithTabs: false, lineNumbers: true, mode: 'javascript', tabSize: 2, theme: 'solarized light', }; const ERROR_TYPES = { graphql: 'GraphQL Validation', query: 'Query', runtime: 'Runtime', schema: 'Schema', syntax: 'Syntax', }; const RENDER_STEP_EXAMPLE_CODE = `ReactDOM.render( <Relay.RootContainer Component={MyRelayContainer} route={new MyHomeRoute()} />, mountNode );`; function errorFromGraphQLResultAndQuery(errors, request) { const queryString = request.getQueryString(); const variables = request.getVariables(); let errorText = ` ${errors.map(e => e.message).join('\n')} Query: ${queryString} `; if (variables) { errorText += `Variables: ${JSON.stringify(variables)}`; } return {stack: errorText.trim()}; } class PlaygroundRenderer extends React.Component { componentDidMount() { this._container = document.createElement('div'); this.refs.mountPoint.appendChild(this._container); this._updateTimeoutId = defer(this._update); } componentDidUpdate(prevProps) { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } this._updateTimeoutId = defer(this._update); } componentWillUnmount() { if (this._updateTimeoutId != null) { clearTimeout(this._updateTimeoutId); } try { ReactDOM.unmountComponentAtNode(this._container); } catch (e) {} } _update = () => { ReactDOM.render(React.Children.only(this.props.children), this._container); } render() { return <div ref="mountPoint" />; } } export default class RelayPlayground extends React.Component { static defaultProps = { autoExecute: false, }; static propTypes = { autoExecute: PropTypes.bool.isRequired, initialAppSource: PropTypes.string, initialSchemaSource: PropTypes.string, onAppSourceChange: PropTypes.func, onSchemaSourceChange: PropTypes.func, }; state = { appElement: null, appSource: this.props.initialAppSource, busy: false, editTarget: 'app', error: null, schemaSource: this.props.initialSchemaSource, shouldExecuteCode: this.props.autoExecute, }; componentDidMount() { // Hijack console.warn to collect GraphQL validation warnings (we hope) this._originalConsoleWarn = console.warn; let collectedWarnings = []; console.warn = (...args) => { collectedWarnings.push([Date.now(), args]); this._originalConsoleWarn.apply(console, args); }; // Hijack window.onerror to catch any stray fatals this._originalWindowOnerror = window.onerror; window.onerror = (message, url, lineNumber, something, error) => { // GraphQL validation warnings are followed closely by a thrown exception. // Console warnings that appear too far before this exception are probably // not related to GraphQL. Throw those out. if (/GraphQL validation error/.test(message)) { const recentWarnings = collectedWarnings .filter(([createdAt, args]) => Date.now() - createdAt <= 500) .reduce((memo, [createdAt, args]) => memo.concat(args), []); this.setState({ error: {stack: recentWarnings.join('\n')}, errorType: ERROR_TYPES.graphql, }); } else { this.setState({error, errorType: ERROR_TYPES.runtime}); } collectedWarnings = []; return false; }; if (this.state.shouldExecuteCode) { this._updateSchema(this.state.schemaSource, this.state.appSource); } } componentDidUpdate(prevProps, prevState) { const recentlyEnabledCodeExecution = !prevState.shouldExecuteCode && this.state.shouldExecuteCode; const appChanged = this.state.appSource !== prevState.appSource; const schemaChanged = this.state.schemaSource !== prevState.schemaSource; if ( this.state.shouldExecuteCode && (recentlyEnabledCodeExecution || appChanged || schemaChanged) ) { this.setState({busy: true}); this._handleSourceCodeChange( this.state.appSource, recentlyEnabledCodeExecution || schemaChanged ? this.state.schemaSource : null, ); } } componentWillUnmount() { clearTimeout(this._errorReporterTimeout); clearTimeout(this._warningScrubberTimeout); this._handleSourceCodeChange.cancel(); console.warn = this._originalConsoleWarn; window.onerror = this._originalWindowOnerror; } _handleExecuteClick = () => { this.setState({shouldExecuteCode: true}); } _handleSourceCodeChange = debounce((appSource, schemaSource) => { if (schemaSource != null) { this._updateSchema(schemaSource, appSource); } else { this._updateApp(appSource); } }, 300, {trailing: true}) _updateApp = (appSource) => { clearTimeout(this._errorReporterTimeout); // We're running in a browser. Create a require() shim to catch any imports. const require = (path) => { switch (path) { // The errorCatcherPlugin injects a series of import statements into the // program body. Return locally bound variables in these three cases: case '//error-catcher.js': return (React, filename, displayName, reporter) => { // When it fatals, render an empty <span /> in place of the app. return errorCatcher(React, filename, <span />, reporter); }; case 'react': return React; case 'reporterProxy': return (error, instance, filename, displayName) => { this._errorReporterTimeout = defer( this.setState.bind(this), {error, errorType: ERROR_TYPES.runtime} ); }; default: throw new Error(`Cannot find module "${path}"`); } }; try { const {code} = transform(appSource, { filename: 'RelayPlayground', plugins : [ babelRelayPlaygroundPlugin, this._babelRelayPlugin, errorCatcherPlugin('reporterProxy'), ], retainLines: true, sourceMaps: 'inline', stage: 0, }); const result = eval(code); if ( React.isValidElement(result) && result.type.name === 'RelayRootContainer' ) { this.setState({ appElement: React.cloneElement(result, {forceFetch: true}), }); } else { this.setState({ appElement: ( <div> <h2> Render a Relay.RootContainer into <code>mountNode</code> to get started. </h2> <p> Example: </p> <pre>{RENDER_STEP_EXAMPLE_CODE}</pre> </div> ), }); } this.setState({error: null}); } catch (error) { this.setState({error, errorType: ERROR_TYPES.syntax}); } this.setState({busy: false}); } _updateCode = (newSource) => { const sourceStorageKey = `${this.state.editTarget}Source`; this.setState({[sourceStorageKey]: newSource}); if (this.state.editTarget === 'app' && this.props.onAppSourceChange) { this.props.onAppSourceChange(newSource); } if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) { this.props.onSchemaSourceChange(newSource); } } _updateEditTarget = (editTarget) => { this.setState({editTarget}); } _updateSchema = (schemaSource, appSource) => { try { var Schema = evalSchema(schemaSource); } catch (error) { this.setState({error, errorType: ERROR_TYPES.schema}); return; } graphql(Schema, introspectionQuery).then((result) => { if ( this.state.schemaSource !== schemaSource || this.state.appSource !== appSource ) { // This version of the code is stale. Bail out. return; } this._babelRelayPlugin = getBabelRelayPlugin(result.data); Relay.injectNetworkLayer( new RelayLocalSchema.NetworkLayer({ schema: Schema, onError: (errors, request) => { this.setState({ error: errorFromGraphQLResultAndQuery(errors, request), errorType: ERROR_TYPES.query, }); }, }) ); this._updateApp(appSource); }); } renderApp() { if (!this.state.shouldExecuteCode) { return ( <div className="rpExecutionGuard"> <div className="rpExecutionGuardMessage"> <h2>For your security, this playground did not auto-execute</h2> <p> Clicking <strong>execute</strong> will run the code in the two tabs to the left. </p> <button onClick={this._handleExecuteClick}>Execute</button> </div> </div> ); } else if (this.state.error) { return ( <div className="rpError"> <h1>{this.state.errorType} Error</h1> <pre className="rpErrorStack">{this.state.error.stack}</pre> </div> ); } else if (this.state.appElement) { return <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer>; } return null; } render() { const sourceCode = this.state.editTarget === 'schema' ? this.state.schemaSource : this.state.appSource; return ( <div className="rpShell"> <section className="rpCodeEditor"> <nav className="rpCodeEditorNav"> <button className={this.state.editTarget === 'app' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'app')}> Code </button> <button className={this.state.editTarget === 'schema' && 'rpButtonActive'} onClick={this._updateEditTarget.bind(this, 'schema')}> Schema </button> </nav> {/* What is going on with the choice of key in Codemirror? * https://github.com/JedWatson/react-codemirror/issues/12 */} <Codemirror key={`${this.state.editTarget}-${this.state.shouldExecuteCode}`} onChange={this._updateCode} options={{ ...CODE_EDITOR_OPTIONS, readOnly: !this.state.shouldExecuteCode, }} value={sourceCode} /> </section> <section className="rpResult"> <h1 className="rpResultHeader"> Relay Playground <span className={ 'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '') } /> </h1> <div className="rpResultOutput"> {this.renderApp()} </div> </section> </div> ); } }
demo/src/index.js
petermoresi/react-table-for-bootstrap
/** * Copyright (c) 2015, Peter W Moresi * */ import React from 'react'; import MyApp from './components/MyApp.js' React.render( <div className="container main"> <h1>Crayola Colors</h1> <MyApp /> </div>, document.body );
app/components/Fields/Group/GroupTile.js
JasonEtco/flintcms
/* eslint-disable jsx-a11y/no-static-element-interactions */ import React from 'react' import PropTypes from 'prop-types' import DeleteIcon from 'components/DeleteIcon' import store from 'utils/store' export default function GroupTile ({ onClick, label, handle, isActive, onDelete }) { const { dispatch } = store return ( <a onClick={onClick} className={`panel__col__tile ${isActive ? 'is-active' : ''}`} > {label} {handle && <span className="panel__col__handle">{handle}</span>} {onDelete && <DeleteIcon onClick={() => onDelete(label)} dispatch={dispatch} />} </a> ) } GroupTile.propTypes = { onClick: PropTypes.func.isRequired, label: PropTypes.string.isRequired, handle: PropTypes.string, isActive: PropTypes.bool.isRequired, onDelete: PropTypes.func } GroupTile.defaultProps = { onDelete: null, handle: null }
src/model/Figure/Footman.js
bigamasta/chess-challenge
/** * Created by BigaMasta on 3/8/16. */ import Figure from './Figure'; import FigureColors from '../../constants/FigureColors'; import React from 'react'; import Positioner from '../../utils/Positioner'; /** * The Footman object that encapsulates all footman specific logic. */ export default class Footman extends Figure { constructor(pos, color, whose) { super(pos, color, whose); } getPossibleMoves() { return Positioner.getAllPositions(); } getRenderable() { if (this.color === FigureColors.BLACK) return (<a>&#9823;</a>); else if (this.color === FigureColors.WHITE) return (<a>&#9817;</a>); } };
node_modules/enzyme/src/ReactWrapper.js
sharonjean/React-Netflix
import React from 'react'; import ComplexSelector from './ComplexSelector'; import cheerio from 'cheerio'; import flatten from 'lodash/flatten'; import unique from 'lodash/uniq'; import compact from 'lodash/compact'; import createWrapperComponent from './ReactWrapperComponent'; import { instHasClassName, childrenOfInst, parentsOfInst, buildInstPredicate, instEqual, treeFilter, getNode, internalInstanceOrComponent, } from './MountedTraversal'; import { renderWithOptions, Simulate, findDOMNode, unmountComponentAtNode, } from './react-compat'; import { mapNativeEventNames, containsChildrenSubArray, propsOfNode, typeOfNode, displayNameOfNode, } from './Utils'; import { debugInsts, } from './Debug'; import { REACT15 } from './version'; /** * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate * function. * * @param {ReactWrapper} wrapper * @param {Function} predicate * @param {Function} filter * @returns {ReactWrapper} */ function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) { return wrapper.flatMap(n => filter(n.node, predicate)); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided predicate function. * * @param {ReactWrapper} wrapper * @param {Function} predicate * @returns {ReactWrapper} */ function filterWhereUnwrapped(wrapper, predicate) { return wrapper.wrap(compact(wrapper.nodes.filter(predicate))); } /** * @class ReactWrapper */ export default class ReactWrapper { constructor(nodes, root, options = {}) { if (!global.window && !global.document) { throw new Error( 'It looks like you called `mount()` without a global document being loaded.' ); } if (!root) { const ReactWrapperComponent = createWrapperComponent(nodes, options); this.component = renderWithOptions( <ReactWrapperComponent Component={nodes.type} props={nodes.props} context={options.context} />, options); this.root = this; this.node = this.component.getWrappedComponent(); this.nodes = [this.node]; this.length = 1; } else { this.component = null; this.root = root; if (!Array.isArray(nodes)) { this.node = nodes; this.nodes = [nodes]; } else { this.node = nodes[0]; this.nodes = nodes; } this.length = this.nodes.length; } this.options = options; this.complexSelector = new ComplexSelector( buildInstPredicate, findWhereUnwrapped, childrenOfInst ); } /** * If the root component contained a ref, you can access it here * and get a wrapper around it. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {String} refname * @returns {ReactWrapper} */ ref(refname) { if (this.root !== this) { throw new Error('ReactWrapper::ref(refname) can only be called on the root'); } return this.wrap(this.instance().refs[refname]); } /** * Gets the instance of the component being rendered as the root node passed into `mount()`. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * Example: * ``` * const wrapper = mount(<MyComponent />); * const inst = wrapper.instance(); * expect(inst).to.be.instanceOf(MyComponent); * ``` * @returns {ReactComponent} */ instance() { if (this.root !== this) { throw new Error('ReactWrapper::instance() can only be called on the root'); } return this.component.getInstance(); } /** * Forces a re-render. Useful to run before checking the render output if something external * may be updating the state of the component somewhere. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @returns {ReactWrapper} */ update() { if (this.root !== this) { // TODO(lmr): this requirement may not be necessary for the ReactWrapper throw new Error('ReactWrapper::update() can only be called on the root'); } this.single(() => { this.component.forceUpdate(); }); return this; } /** * A method that unmounts the component. This can be used to simulate a component going through * and unmount/mount lifecycle. * * @returns {ReactWrapper} */ unmount() { if (this.root !== this) { throw new Error('ReactWrapper::unmount() can only be called on the root'); } this.single(() => { this.component.setState({ mount: false }); }); return this; } /** * A method that re-mounts the component. This can be used to simulate a component going through * an unmount/mount lifecycle. * * @returns {ReactWrapper} */ mount() { if (this.root !== this) { throw new Error('ReactWrapper::mount() can only be called on the root'); } this.single(() => { this.component.setState({ mount: true }); }); return this; } /** * A method that sets the props of the root component, and re-renders. Useful for when you are * wanting to test how the component behaves over time with changing props. Calling this, for * instance, will call the `componentWillReceiveProps` lifecycle method. * * Similar to `setState`, this method accepts a props object and will merge it in with the already * existing props. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} props object * @returns {ReactWrapper} */ setProps(props) { if (this.root !== this) { throw new Error('ReactWrapper::setProps() can only be called on the root'); } this.component.setChildProps(props); return this; } /** * A method to invoke `setState` on the root component instance similar to how you might in the * definition of the component, and re-renders. This method is useful for testing your component * in hard to achieve states, however should be used sparingly. If possible, you should utilize * your component's external API in order to get it into whatever state you want to test, in order * to be as accurate of a test as possible. This is not always practical, however. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} state to merge * @returns {ReactWrapper} */ setState(state) { if (this.root !== this) { throw new Error('ReactWrapper::setState() can only be called on the root'); } this.instance().setState(state); return this; } /** * A method that sets the context of the root component, and re-renders. Useful for when you are * wanting to test how the component behaves over time with changing contexts. * * NOTE: can only be called on a wrapper instance that is also the root instance. * * @param {Object} context object * @returns {ReactWrapper} */ setContext(context) { if (this.root !== this) { throw new Error('ReactWrapper::setContext() can only be called on the root'); } if (!this.options.context) { throw new Error( 'ShallowWrapper::setContext() can only be called on a wrapper that was originally passed ' + 'a context option' ); } this.component.setChildContext(context); return this; } /** * Whether or not a given react element matches the current render tree. * It will determine if the wrapper root node "looks like" the expected * element by checking if all props of the expected element are present * on the wrapper root node and equals to each other. * * Example: * ``` * // MyComponent outputs <div class="foo">Hello</div> * const wrapper = mount(<MyComponent />); * expect(wrapper.matchesElement(<div>Hello</div>)).to.equal(true); * ``` * * @param {ReactElement} node * @returns {Boolean} */ matchesElement(node) { return this.single(() => instEqual(node, this.node, (a, b) => a <= b)); } /** * Whether or not a given react element exists in the mount render tree. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true); * ``` * * @param {ReactElement|Array<ReactElement>} nodeOrNodes * @returns {Boolean} */ contains(nodeOrNodes) { const predicate = Array.isArray(nodeOrNodes) ? other => containsChildrenSubArray(instEqual, other, nodeOrNodes) : other => instEqual(nodeOrNodes, other); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not a given react element exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * // MyComponent outputs <div><div class="foo">Hello</div></div> * const wrapper = mount(<MyComponent />); * expect(wrapper.containsMatchingElement(<div>Hello</div>)).to.equal(true); * ``` * * @param {ReactElement} node * @returns {Boolean} */ containsMatchingElement(node) { const predicate = other => instEqual(node, other, (a, b) => a <= b); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not all the given react elements exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.containsAllMatchingElements([ * <div>Hello</div>, * <div>Goodbye</div>, * ])).to.equal(true); * ``` * * @param {Array<ReactElement>} nodes * @returns {Boolean} */ containsAllMatchingElements(nodes) { const invertedEquals = (n1, n2) => instEqual(n2, n1, (a, b) => a <= b); const predicate = other => containsChildrenSubArray(invertedEquals, other, nodes); return findWhereUnwrapped(this, predicate).length > 0; } /** * Whether or not one of the given react elements exists in the current render tree. * It will determine if one of the wrappers element "looks like" the expected * element by checking if all props of the expected element are present * on the wrappers element and equals to each other. * * Example: * ``` * const wrapper = mount(<MyComponent />); * expect(wrapper.containsAnyMatchingElements([ * <div>Hello</div>, * <div>Goodbye</div>, * ])).to.equal(true); * ``` * * @param {Array<ReactElement>} nodes * @returns {Boolean} */ containsAnyMatchingElements(nodes) { if (!Array.isArray(nodes)) return false; if (nodes.length <= 0) return false; for (let i = 0; i < nodes.length; i++) { if (this.containsMatchingElement(nodes[i])) { return true; } } return false; } /** * Finds every node in the render tree of the current wrapper that matches the provided selector. * * @param {String|Function} selector * @returns {ReactWrapper} */ find(selector) { return this.complexSelector.find(selector, this); } /** * Returns whether or not current node matches a provided selector. * * NOTE: can only be called on a wrapper of a single node. * * @param {String|Function} selector * @returns {boolean} */ is(selector) { const predicate = buildInstPredicate(selector); return this.single(n => predicate(n)); } /** * Returns true if the component rendered nothing, i.e., null or false. * * @returns {boolean} */ isEmptyRender() { return this.single((n) => { // Stateful components and stateless function components have different internal structures, // so we need to find the correct internal instance, and validate the rendered node type // equals 2, which is the `ReactNodeTypes.EMPTY` value. if (REACT15) { return internalInstanceOrComponent(n)._renderedNodeType === 2; } return findDOMNode(n) === null; }); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided predicate function. * * @param {Function} predicate * @returns {ReactWrapper} */ filterWhere(predicate) { return filterWhereUnwrapped(this, n => predicate(this.wrap(n))); } /** * Returns a new wrapper instance with only the nodes of the current wrapper instance that match * the provided selector. * * @param {String|Function} selector * @returns {ReactWrapper} */ filter(selector) { const predicate = buildInstPredicate(selector); return filterWhereUnwrapped(this, predicate); } /** * Returns a new wrapper instance with only the nodes of the current wrapper that did not match * the provided selector. Essentially the inverse of `filter`. * * @param {String|Function} selector * @returns {ReactWrapper} */ not(selector) { const predicate = buildInstPredicate(selector); return filterWhereUnwrapped(this, n => !predicate(n)); } /** * Returns a string of the rendered text of the current render tree. This function should be * looked at with skepticism if being used to test what the actual HTML output of the component * will be. If that is what you would like to test, use enzyme's `render` function instead. * * NOTE: can only be called on a wrapper of a single node. * * @returns {String} */ text() { return this.single(n => findDOMNode(n).textContent); } /** * Returns the HTML of the node. * * NOTE: can only be called on a wrapper of a single node. * * @returns {String} */ html() { return this.single(n => { const node = findDOMNode(n); return node === null ? null : node.outerHTML.replace(/\sdata-(reactid|reactroot)+="([^"]*)+"/g, ''); }); } /** * Returns the current node rendered to HTML and wrapped in a CheerioWrapper. * * NOTE: can only be called on a wrapper of a single node. * * @returns {CheerioWrapper} */ render() { const html = this.html(); return html === null ? cheerio() : cheerio.load(html).root(); } /** * Used to simulate events. Pass an eventname and (optionally) event arguments. This method of * testing events should be met with some skepticism. * * @param {String} event * @param {Object} mock (optional) * @returns {ReactWrapper} */ simulate(event, mock = {}) { this.single(n => { const mappedEvent = mapNativeEventNames(event); const eventFn = Simulate[mappedEvent]; if (!eventFn) { throw new TypeError(`ReactWrapper::simulate() event '${event}' does not exist`); } eventFn(findDOMNode(n), mock); }); return this; } /** * Returns the props hash for the root node of the wrapper. * * NOTE: can only be called on a wrapper of a single node. * * @returns {Object} */ props() { return this.single(propsOfNode); } /** * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it * will return just that value. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} name (optional) * @returns {*} */ state(name) { if (this.root !== this) { throw new Error('ReactWrapper::state() can only be called on the root'); } const _state = this.single(() => this.instance().state); if (name !== undefined) { return _state[name]; } return _state; } /** * Returns the context hash for the root node of the wrapper. * Optionally pass in a prop name and it will return just that value. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} name (optional) * @returns {*} */ context(name) { if (this.root !== this) { throw new Error('ReactWrapper::context() can only be called on the root'); } const _context = this.single(() => this.instance().context); if (name !== undefined) { return _context[name]; } return _context; } /** * Returns a new wrapper with all of the children of the current wrapper. * * @param {String|Function} [selector] * @returns {ReactWrapper} */ children(selector) { const allChildren = this.flatMap(n => childrenOfInst(n.node)); return selector ? allChildren.filter(selector) : allChildren; } /** * Returns a new wrapper with a specific child * * @param {Number} [index] * @returns {ReactWrapper} */ childAt(index) { return this.single(() => this.children().at(index)); } /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node * in the current wrapper. * * NOTE: can only be called on a wrapper of a single node. * * @param {String|Function} [selector] * @returns {ReactWrapper} */ parents(selector) { const allParents = this.wrap(this.single(n => parentsOfInst(n, this.root.node))); return selector ? allParents.filter(selector) : allParents; } /** * Returns a wrapper around the immediate parent of the current node. * * @returns {ReactWrapper} */ parent() { return this.flatMap(n => [n.parents().get(0)]); } /** * * @param {String|Function} selector * @returns {ReactWrapper} */ closest(selector) { return this.is(selector) ? this : this.parents().filter(selector).first(); } /** * Returns the value of prop with the given name of the root node. * * @param {String} propName * @returns {*} */ prop(propName) { return this.props()[propName]; } /** * Returns the key assigned to the current node. * * @returns {String} */ key() { return this.single((n) => getNode(n).key); } /** * Returns the type of the root node of this wrapper. If it's a composite component, this will be * the component constructor. If it's native DOM node, it will be a string. * * @returns {String|Function} */ type() { return this.single(n => typeOfNode(getNode(n))); } /** * Returns the name of the root node of this wrapper. * * In order of precedence => type.displayName -> type.name -> type. * * @returns {String} */ name() { return this.single(n => displayNameOfNode(getNode(n))); } /** * Returns whether or not the current root node has the given class name or not. * * NOTE: can only be called on a wrapper of a single node. * * @param {String} className * @returns {Boolean} */ hasClass(className) { if (className && className.indexOf('.') !== -1) { // eslint-disable-next-line no-console console.warn( 'It looks like you\'re calling `ReactWrapper::hasClass()` with a CSS selector. ' + 'hasClass() expects a class name, not a CSS selector.' ); } return this.single(n => instHasClassName(n, className)); } /** * Iterates through each node of the current wrapper and executes the provided function with a * wrapper around the corresponding node passed in as the first argument. * * @param {Function} fn * @returns {ReactWrapper} */ forEach(fn) { this.nodes.forEach((n, i) => fn.call(this, this.wrap(n), i)); return this; } /** * Maps the current array of nodes to another array. Each node is passed in as a `ReactWrapper` * to the map function. * * @param {Function} fn * @returns {Array} */ map(fn) { return this.nodes.map((n, i) => fn.call(this, this.wrap(n), i)); } /** * Reduces the current array of nodes to another array. * Each node is passed in as a `ShallowWrapper` to the reducer function. * * @param {Function} fn - the reducer function * @param {*} initialValue - the initial value * @returns {*} */ reduce(fn, initialValue) { return this.nodes.reduce( (accum, n, i) => fn.call(this, accum, this.wrap(n), i), initialValue ); } /** * Reduces the current array of nodes to another array, from right to left. Each node is passed * in as a `ShallowWrapper` to the reducer function. * * @param {Function} fn - the reducer function * @param {*} initialValue - the initial value * @returns {*} */ reduceRight(fn, initialValue) { return this.nodes.reduceRight( (accum, n, i) => fn.call(this, accum, this.wrap(n), i), initialValue ); } /** * Returns whether or not any of the nodes in the wrapper match the provided selector. * * @param {Function|String} selector * @returns {Boolean} */ some(selector) { const predicate = buildInstPredicate(selector); return this.nodes.some(predicate); } /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * * @param {Function} predicate * @returns {Boolean} */ someWhere(predicate) { return this.nodes.some((n, i) => predicate.call(this, this.wrap(n), i)); } /** * Returns whether or not all of the nodes in the wrapper match the provided selector. * * @param {Function|String} selector * @returns {Boolean} */ every(selector) { const predicate = buildInstPredicate(selector); return this.nodes.every(predicate); } /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * * @param {Function} predicate * @returns {Boolean} */ everyWhere(predicate) { return this.nodes.every((n, i) => predicate.call(this, this.wrap(n), i)); } /** * Utility method used to create new wrappers with a mapping function that returns an array of * nodes in response to a single node wrapper. The returned wrapper is a single wrapper around * all of the mapped nodes flattened (and de-duplicated). * * @param {Function} fn * @returns {ReactWrapper} */ flatMap(fn) { const nodes = this.nodes.map((n, i) => fn.call(this, this.wrap(n), i)); const flattened = flatten(nodes, true); const uniques = unique(flattened); const compacted = compact(uniques); return this.wrap(compacted); } /** * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate * function. * * @param {Function} predicate * @returns {ReactWrapper} */ findWhere(predicate) { return findWhereUnwrapped(this, n => predicate(this.wrap(n))); } /** * Returns the node at a given index of the current wrapper. * * @param {Number} index * @returns {ReactElement} */ get(index) { return this.nodes[index]; } /** * Returns a wrapper around the node at a given index of the current wrapper. * * @param {Number} index * @returns {ReactWrapper} */ at(index) { return this.wrap(this.nodes[index]); } /** * Returns a wrapper around the first node of the current wrapper. * * @returns {ReactWrapper} */ first() { return this.at(0); } /** * Returns a wrapper around the last node of the current wrapper. * * @returns {ReactWrapper} */ last() { return this.at(this.length - 1); } /** * Returns true if the current wrapper has no nodes. False otherwise. * * @returns {boolean} */ isEmpty() { return this.length === 0; } /** * Utility method that throws an error if the current instance has a length other than one. * This is primarily used to enforce that certain methods are only run on a wrapper when it is * wrapping a single node. * * @param {Function} fn * @returns {*} */ single(fn) { if (this.length !== 1) { throw new Error( `This method is only meant to be run on single node. ${this.length} found instead.` ); } return fn.call(this, this.node); } /** * Helpful utility method to create a new wrapper with the same root as the current wrapper, with * any nodes passed in as the first parameter automatically wrapped. * * @param {ReactWrapper|ReactElement|Array<ReactElement>} node * @returns {ReactWrapper} */ wrap(node) { if (node instanceof ReactWrapper) { return node; } return new ReactWrapper(node, this.root); } /** * Returns an HTML-like string of the shallow render for debugging purposes. * * @returns {String} */ debug() { return debugInsts(this.nodes); } /** * Invokes intercepter and returns itself. intercepter is called with itself. * This is helpful when debugging nodes in method chains. * @param fn * @returns {ReactWrapper} */ tap(intercepter) { intercepter(this); return this; } /** * Detaches the react tree from the DOM. Runs `ReactDOM.unmountComponentAtNode()` under the hood. * * This method will most commonly be used as a "cleanup" method if you decide to use the * `attachTo` option in `mount(node, options)`. * * The method is intentionally not "fluent" (in that it doesn't return `this`) because you should * not be doing anything with this wrapper after this method is called. */ detach() { if (this.root !== this) { throw new Error('ReactWrapper::detach() can only be called on the root'); } if (!this.options.attachTo) { throw new Error( 'ReactWrapper::detach() can only be called on when the `attachTo` option was passed into ' + '`mount()`.' ); } unmountComponentAtNode(this.options.attachTo); } }
src/svg-icons/action/print.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPrint = (props) => ( <SvgIcon {...props}> <path d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/> </SvgIcon> ); ActionPrint = pure(ActionPrint); ActionPrint.displayName = 'ActionPrint'; ActionPrint.muiName = 'SvgIcon'; export default ActionPrint;
src/common/components/Heading.js
TheoMer/este
// @flow import type { TextProps } from './Text'; import type { Theme } from '../themes/types'; import Text from './Text'; import React from 'react'; type HeadingContext = { theme: Theme, }; const Heading = (props: TextProps, { theme }: HeadingContext) => { const { bold = true, fontFamily = theme.heading.fontFamily, marginBottom = theme.heading.marginBottom, ...restProps } = props; return ( <Text bold={bold} fontFamily={fontFamily} marginBottom={marginBottom} {...restProps} /> ); }; Heading.contextTypes = { theme: React.PropTypes.object, }; export default Heading;
src/beforeRouteReadyRender.js
foysavas/react-route-ready
import React from 'react'; import PropTypes from 'prop-types'; export default function beforeRouteReadyRender(renderer) { return (Component) => { Component.contextTypes = Object.assign(Component.contextTypes, { reactRouteReadyLoading: PropTypes.bool.isRequired, reactRouteReadyLoaded: PropTypes.bool.isRequired, reactRouteReadyComponentStatus: PropTypes.object.isRequired }) const __render = Component.prototype.render; Component.prototype.render = function() { const routeComponent = this.props.route.component; const compStatus = this.context.reactRouteReadyComponentStatus.get(routeComponent); const wasRouteLoaded = this.context.reactRouteReadyLoaded; const isRouteLoading = this.context.reactRouteReadyLoading; const isStarting = !isRouteLoading && !wasRouteLoaded; const isCompLoading = isRouteLoading && (compStatus === "queued" || compStatus === "loading"); if (isStarting || isCompLoading) { return React.createElement(renderer, this.props); } else { return __render.apply(this); } } return Component; }; }
src/svg-icons/image/blur-off.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBlurOff = (props) => ( <SvgIcon {...props}> <path d="M14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-.2 4.48l.2.02c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5l.02.2c.09.67.61 1.19 1.28 1.28zM14 3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-4 0c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm11 7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8 8c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-4 13.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM2.5 5.27l3.78 3.78L6 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l2.81 2.81c-.71.11-1.25.73-1.25 1.47 0 .83.67 1.5 1.5 1.5.74 0 1.36-.54 1.47-1.25l2.81 2.81c-.09-.03-.18-.06-.28-.06-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l3.78 3.78L20 20.23 3.77 4 2.5 5.27zM10 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm11-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 11c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5z"/> </SvgIcon> ); ImageBlurOff = pure(ImageBlurOff); ImageBlurOff.displayName = 'ImageBlurOff'; ImageBlurOff.muiName = 'SvgIcon'; export default ImageBlurOff;
docs/src/examples/views/Feed/Content/FeedExampleExtraImages.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Feed } from 'semantic-ui-react' const FeedExampleAdditionalInformation = () => ( <Feed> <Feed.Event> <Feed.Label image='/images/avatar/small/helen.jpg' /> <Feed.Content> <Feed.Date>3 days ago</Feed.Date> <Feed.Summary> <a>Helen Troy</a> added 2 photos </Feed.Summary> <Feed.Extra images> <a> <img src='/images/wireframe/image.png' /> </a> <a> <img src='/images/wireframe/image.png' /> </a> </Feed.Extra> </Feed.Content> </Feed.Event> </Feed> ) export default FeedExampleAdditionalInformation
src/components/App/App.js
OSBI/saiku-react-starter
/** * Copyright 2017 OSBI Ltd * * 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, { Component } from 'react'; import { Link } from 'react-router'; import { Grid, Navbar, Nav, NavItem } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import style from './App.styl'; class App extends Component { render() { return ( <div> <Navbar fixedTop inverse collapseOnSelect> <Navbar.Header> <Navbar.Brand> <Link to="/">Project name</Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <LinkContainer to="/"> <NavItem eventKey={1}>Home</NavItem> </LinkContainer> <LinkContainer to="/filter"> <NavItem eventKey={2}>Filter Product</NavItem> </LinkContainer> <LinkContainer to="/about"> <NavItem eventKey={3}>About</NavItem> </LinkContainer> <LinkContainer to="/contact"> <NavItem eventKey={4}>Contact</NavItem> </LinkContainer> </Nav> </Navbar.Collapse> </Navbar> <Grid> <div className={style.App}> {React.cloneElement(this.props.children, this.props)} </div> </Grid> </div> ); } } export default App;
client/app/components/App.js
RichHomies/ReactorMaker
import React from 'react'; import Navbar from './Navbar'; import Footer from './Footer'; var App = React.createClass({ render: function() { return ( <div> <Navbar /> {this.props.children} <Footer /> </div> ); } }) export default App;
src/client/components/SectionHeaderWidget/SectionHeaderWidget.js
vidaaudrey/trippian
import log from '../../log' import React from 'react' import { SectionHeaderWidget as appConfig } from '../../config/appConfig' const SectionHeaderWidget = ({ title = appConfig.title, subTitle = appConfig.subTitle }) => { return ( <div className="section-header text-center"> <h2>{title}</h2> {subTitle && <p>{subTitle}</p> } </div> ) } SectionHeaderWidget.displayName = 'SectionHeaderWidget' export default SectionHeaderWidget
src/features/home/ColResizer.js
supnate/command-pad
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import classnames from 'classnames'; import { setColWidth } from './redux/actions'; export class ColResizer extends Component { static propTypes = { colWidth: PropTypes.number.isRequired, actions: PropTypes.object.isRequired, }; state = { dragging: false, }; assignRef = node => { this.node = node; }; handleMouseDown = evt => { this.setState({ dragging: true }); }; handleMouseMove = (evt) => { if (!this.state.dragging) return; this.props.actions.setColWidth(evt.pageX); window.dispatchEvent(new window.Event('resize')); }; handleMouseUp = () => { this.setState({ dragging: false }); }; render() { return ( <div className={classnames('home-col-resizer', { 'is-dragging': this.state.dragging })} style={{ left: `${this.props.colWidth}px` }} ref={this.assignRef} onMouseUp={this.handleMouseUp} onMouseMove={this.handleMouseMove} > <div className="true-resizer" style={{ left: `${this.state.dragging ? this.props.colWidth : 0}px` }} onMouseDown={this.handleMouseDown} /> </div> ); } } /* istanbul ignore next */ function mapStateToProps(state) { return { colWidth: state.home.colWidth, }; } /* istanbul ignore next */ function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ setColWidth }, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(ColResizer);
src/app/pin/components/PinList.js
brandondewitt/react-pinterest-clone
import React, { Component } from 'react'; import { Link } from 'react-router'; import { Table } from 'react-bootstrap'; import { PinDetail } from 'pin/components/PinDetail'; export class PinList extends Component { constructor() { super(); this.state = {}; } render() { const pins = this.props.pins.map(pin => ( <div className="col-md-4 col-sm-6" key={pin.id} > <PinDetail {...pin}></PinDetail> </div> )); return ( <div className="row"> {pins} </div> ); } }
demo/Button.js
szchenghuang/react-mdui
'use strict'; //############################################################################# // Stylesheets. //############################################################################# //############################################################################# // Library includes. //############################################################################# import React from 'react'; import { Button, Icon } from '../'; //############################################################################# // Application includes. //############################################################################# //############################################################################# // Constants. //############################################################################# const examples = [ { label: 'Flat buttons', demo: ( <div> <p> <Button>button</Button> </p> <p> <Button disabled>disabled</Button> </p> </div> ), code: `<Button>button</Button> <Button disabled>disabled</Button>` }, { label: 'Raised buttons', demo: ( <div> <p> <Button raised>button</Button> </p> <p> <Button raised disabled>disabled</Button> </p> </div> ), code: `<Button raised>button</Button> <Button raised disabled>disabled</Button>` }, { label: 'Icon buttons', demo: ( <div> <p> <Button icon><Icon materialIcon="add" /></Button> </p> <p> <Button><Icon materialIcon="share" right/> Share</Button> </p> <p> <Button><Icon materialIcon="share" left/> Share</Button> </p> <p> <Button disabled><Icon materialIcon="share" left/> Share</Button> </p> </div> ), code: `<Button icon><Icon materialIcon="add" /></Button> <Button><Icon materialIcon="share" right /> Share</Button> <Button><Icon materialIcon="share" left /> Share</Button> <Button disabled><Icon materialIcon="share" left /> Share</Button>` } ]; export default examples;
src/svg-icons/image/photo-library.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoLibrary = (props) => ( <SvgIcon {...props}> <path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/> </SvgIcon> ); ImagePhotoLibrary = pure(ImagePhotoLibrary); ImagePhotoLibrary.displayName = 'ImagePhotoLibrary'; ImagePhotoLibrary.muiName = 'SvgIcon'; export default ImagePhotoLibrary;
react/features/settings/components/web/audio/AudioSettingsContent.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { translate } from '../../../../base/i18n'; import { IconMicrophoneHollow, IconVolumeEmpty } from '../../../../base/icons'; import JitsiMeetJS from '../../../../base/lib-jitsi-meet'; import { equals } from '../../../../base/redux'; import { createLocalAudioTracks } from '../../../functions'; import AudioSettingsHeader from './AudioSettingsHeader'; import MicrophoneEntry from './MicrophoneEntry'; import SpeakerEntry from './SpeakerEntry'; const browser = JitsiMeetJS.util.browser; /** * Translates the default device label into a more user friendly one. * * @param {string} deviceId - The device Id. * @param {string} label - The device label. * @param {Function} t - The translation function. * @returns {string} */ function transformDefaultDeviceLabel(deviceId, label, t) { return deviceId === 'default' ? t('settings.sameAsSystem', { label: label.replace('Default - ', '') }) : label; } export type Props = { /** * The deviceId of the microphone in use. */ currentMicDeviceId: string, /** * The deviceId of the output device in use. */ currentOutputDeviceId: string, /** * Used to decide whether to measure audio levels for microphone devices. */ measureAudioLevels: boolean, /** * Used to set a new microphone as the current one. */ setAudioInputDevice: Function, /** * Used to set a new output device as the current one. */ setAudioOutputDevice: Function, /** * A list of objects containing the labels and deviceIds * of all the output devices. */ outputDevices: Object[], /** * A list with objects containing the labels and deviceIds * of all the input devices. */ microphoneDevices: Object[], /** * Invoked to obtain translated strings. */ t: Function }; type State = { /** * An list of objects, each containing the microphone label, audio track, device id * and track error if the case. */ audioTracks: Object[] } /** * Implements a React {@link Component} which displays a list of all * the audio input & output devices to choose from. * * @augments Component */ class AudioSettingsContent extends Component<Props, State> { _componentWasUnmounted: boolean; _audioContentRef: Object; microphoneHeaderId = 'microphone_settings_header'; speakerHeaderId = 'speaker_settings_header'; /** * Initializes a new {@code AudioSettingsContent} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); this._onMicrophoneEntryClick = this._onMicrophoneEntryClick.bind(this); this._onSpeakerEntryClick = this._onSpeakerEntryClick.bind(this); this._onEscClick = this._onEscClick.bind(this); this._audioContentRef = React.createRef(); this.state = { audioTracks: props.microphoneDevices.map(({ deviceId, label }) => { return { deviceId, hasError: false, jitsiTrack: null, label }; }) }; } _onEscClick: (KeyboardEvent) => void; /** * Click handler for the speaker entries. * * @param {KeyboardEvent} event - Esc key click to close the popup. * @returns {void} */ _onEscClick(event) { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this._audioContentRef.current.style.display = 'none'; } } _onMicrophoneEntryClick: (string) => void; /** * Click handler for the microphone entries. * * @param {string} deviceId - The deviceId for the clicked microphone. * @returns {void} */ _onMicrophoneEntryClick(deviceId) { this.props.setAudioInputDevice(deviceId); } _onSpeakerEntryClick: (string) => void; /** * Click handler for the speaker entries. * * @param {string} deviceId - The deviceId for the clicked speaker. * @returns {void} */ _onSpeakerEntryClick(deviceId) { this.props.setAudioOutputDevice(deviceId); } /** * Renders a single microphone entry. * * @param {Object} data - An object with the deviceId, jitsiTrack & label of the microphone. * @param {number} index - The index of the element, used for creating a key. * @param {length} length - The length of the microphone list. * @param {Function} t - The translation function. * @returns {React$Node} */ _renderMicrophoneEntry(data, index, length, t) { const { deviceId, jitsiTrack, hasError } = data; const label = transformDefaultDeviceLabel(deviceId, data.label, t); const isSelected = deviceId === this.props.currentMicDeviceId; return ( <MicrophoneEntry deviceId = { deviceId } hasError = { hasError } index = { index } isSelected = { isSelected } jitsiTrack = { jitsiTrack } key = { `me-${index}` } length = { length } listHeaderId = { this.microphoneHeaderId } measureAudioLevels = { this.props.measureAudioLevels } onClick = { this._onMicrophoneEntryClick }> {label} </MicrophoneEntry> ); } /** * Renders a single speaker entry. * * @param {Object} data - An object with the deviceId and label of the speaker. * @param {number} index - The index of the element, used for creating a key. * @param {length} length - The length of the speaker list. * @param {Function} t - The translation function. * @returns {React$Node} */ _renderSpeakerEntry(data, index, length, t) { const { deviceId } = data; const label = transformDefaultDeviceLabel(deviceId, data.label, t); const key = `se-${index}`; const isSelected = deviceId === this.props.currentOutputDeviceId; return ( <SpeakerEntry deviceId = { deviceId } index = { index } isSelected = { isSelected } key = { key } length = { length } listHeaderId = { this.speakerHeaderId } onClick = { this._onSpeakerEntryClick }> {label} </SpeakerEntry> ); } /** * Creates and updates the audio tracks. * * @returns {void} */ async _setTracks() { if (browser.isWebKitBased()) { // It appears that at the time of this writing, creating audio tracks blocks the browser's main thread for // long time on safari. Wasn't able to confirm which part of track creation does the blocking exactly, but // not creating the tracks seems to help and makes the UI much more responsive. return; } this._disposeTracks(this.state.audioTracks); const audioTracks = await createLocalAudioTracks(this.props.microphoneDevices, 5000); if (this._componentWasUnmounted) { this._disposeTracks(audioTracks); } else { this.setState({ audioTracks }); } } /** * Disposes the audio tracks. * * @param {Object} audioTracks - The object holding the audio tracks. * @returns {void} */ _disposeTracks(audioTracks) { audioTracks.forEach(({ jitsiTrack }) => { jitsiTrack && jitsiTrack.dispose(); }); } /** * Implements React's {@link Component#componentDidMount}. * * @inheritdoc */ componentDidMount() { this._setTracks(); } /** * Implements React's {@link Component#componentWillUnmount}. * * @inheritdoc */ componentWillUnmount() { this._componentWasUnmounted = true; this._disposeTracks(this.state.audioTracks); } /** * Implements React's {@link Component#componentDidUpdate}. * * @inheritdoc */ componentDidUpdate(prevProps) { if (!equals(this.props.microphoneDevices, prevProps.microphoneDevices)) { this._setTracks(); } } /** * Implements React's {@link Component#render}. * * @inheritdoc */ render() { const { outputDevices, t } = this.props; return ( <div> <div aria-labelledby = 'audio-settings-button' className = 'audio-preview-content' id = 'audio-settings-dialog' onKeyDown = { this._onEscClick } ref = { this._audioContentRef } role = 'menu' tabIndex = { -1 }> <div role = 'menuitem'> <AudioSettingsHeader IconComponent = { IconMicrophoneHollow } id = { this.microphoneHeaderId } text = { t('settings.microphones') } /> <ul aria-labelledby = 'microphone_settings_header' className = 'audio-preview-content-ul' role = 'radiogroup' tabIndex = '-1'> {this.state.audioTracks.map((data, i) => this._renderMicrophoneEntry(data, i, this.state.audioTracks.length, t) )} </ul> </div> { outputDevices.length > 0 && ( <div role = 'menuitem'> <hr className = 'audio-preview-hr' /> <AudioSettingsHeader IconComponent = { IconVolumeEmpty } id = { this.speakerHeaderId } text = { t('settings.speakers') } /> <ul aria-labelledby = 'speaker_settings_header' className = 'audio-preview-content-ul' role = 'radiogroup' tabIndex = '-1'> { outputDevices.map((data, i) => this._renderSpeakerEntry(data, i, outputDevices.length, t) )} </ul> </div>) } </div> </div> ); } } export default translate(AudioSettingsContent);
src/Components/Form/Form.js
PaulPourtout/datathon-ajis
import React, { Component } from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import Paper from 'material-ui/Paper'; const handicapType = [ <MenuItem key={1} value={1} primaryText="Handicap auditif" />, <MenuItem key={2} value={2} primaryText="Handicap mental" />, <MenuItem key={3} value={3} primaryText="Handicap moteur" />, <MenuItem key={4} value={4} primaryText="Handicap psychique" />, <MenuItem key={5} value={5} primaryText="Handicap visuel" />, <MenuItem key={6} value={6} primaryText="Maladie invalidante" />, <MenuItem key={7} value={7} primaryText="Multi-handicap" />, ]; const categorieSp = [ <MenuItem key={1} value={1} primaryText="Agriculteurs et exploitants" />, <MenuItem key={2} value={2} primaryText="Artisans, commerçants et chefs d’entreprise" />, <MenuItem key={3} value={3} primaryText="Cadres et professions intellectuelles supérieures" />, <MenuItem key={4} value={4} primaryText="Professions intermédiaires" />, <MenuItem key={5} value={5} primaryText="Employés" />, <MenuItem key={6} value={6} primaryText="Ouvriers" />, ]; const genre = [ <MenuItem key={1} value={1} primaryText="Homme" />, <MenuItem key={2} value={2} primaryText="Femme" />, ]; const stylePaper = { height: 100, width: 900, margin: 20, display: 'flex', justifyContent: "space-around" }; /** * `SelectField` supports a floating label with the `floatingLabelText` property. * This can be fixed in place with the `floatingLabelFixed` property, * and can be customised with the `floatingLabelText` property. */ export default class Form extends Component { state = { value: null, value2: null, value3: null }; handleChange = (event, index, value) => this.setState({ value }); handleChange2 = (event, index, value2) => this.setState({ value2 }); handleChange3 = (event, index, value3) => this.setState({ value3 }); render() { return ( <Paper style={stylePaper} zDepth={3} > <SelectField value={this.state.value} onChange={this.handleChange} floatingLabelText="Type de handicap" > {handicapType} </SelectField> <br /> <SelectField value={this.state.value2} onChange={this.handleChange2} floatingLabelText="Catégorie socio-professionnelle" > {categorieSp} </SelectField> <br /> <SelectField value={this.state.value3} onChange={this.handleChange3} floatingLabelText="Genre" > {genre} </SelectField> </Paper> ); } }
src/parser/warlock/destruction/CONFIG.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import { Chizu } from 'CONTRIBUTORS'; import SPECS from 'game/SPECS'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [Chizu], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.1', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Hello fellow Netherlords! With some help from <strong>Motoko</strong> from Warlock Discord, we've put together this tool to help you improve your gameplay. It should be fine for you generally, but it will be even more useful in an expert's hands. <br /> <br /> If you have any questions about Warlocks, feel free to pay a visit to <a href="https://discord.gg/BlackHarvest" target="_blank" rel="noopener noreferrer">Council of the Black Harvest Discord</a>&nbsp; or <a href="http://lockonestopshop.com" target="_blank" rel="noopener noreferrer">Lock One Stop Shop</a>, if you'd like to discuss anything about this analyzer, message me @Chizu#2873 on WoWAnalyzer Discord. </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/3-Lunaira', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.DESTRUCTION_WARLOCK, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => import('./CombatLogParser' /* webpackChunkName: "DestructionWarlock" */).then(exports => exports.default), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
src/svg-icons/content/filter-list.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFilterList = (props) => ( <SvgIcon {...props}> <path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/> </SvgIcon> ); ContentFilterList = pure(ContentFilterList); ContentFilterList.displayName = 'ContentFilterList'; ContentFilterList.muiName = 'SvgIcon'; export default ContentFilterList;
app/containers/RecipesContainers.js
Right-Men/Birdman
import React from 'react'; import {connect} from 'react-redux'; import Recipe from '../pages/Recipe'; class RecipesContainers extends React.Component { render() { return ( <Recipe {...this.props} /> ) } } export default connect((state) => { const { Recipe } = state; return { Recipe } })(RecipesContainers);
OrgView.js
dmrd/org_squared
let Org = require('./org/org'); let Parser = require('./org/org_parser'); let Moment = require('moment'); import { Router } from './Router' import { withNavigation, NavigationActions, StackNavigation, DrawerNavigation, DrawerNavigationItem, } from '@exponent/ex-navigation'; import { StyleSheet, } from 'react-native'; import { Entypo, MaterialIcons } from '@exponent/vector-icons'; import { connect } from 'react-redux'; import { Icon, SearchBar } from 'react-native-elements' import { SideMenu, List, ListItem } from 'react-native-elements' import React, { Component } from 'react'; import Menu, { MenuOptions, MenuOption, MenuTrigger } from 'react-native-menu'; import Swipeout from 'react-native-swipeout'; import { ListView, Picker, Text, TextInput, TouchableHighlight, TouchableWithoutFeedback, ScrollView, View } from 'react-native'; /***** Actions *****/ // Toggle node visibility in outline view const TOGGLE_VISIBILITY = 'TOGGLE_VISIBLE'; // Set a node property. [field, path] + value const SET_PROPERTY = 'SET_FOCUSED_PROPERTY'; // Focus on a single node const SET_FOCUS = 'SET_FOCUS'; // Clear single node focus const CLEAR_FOCUS = 'CLEAR_FOCUS'; // Set search term const SEARCH = 'SEARCH'; // Push a nav route const PUSH_ROUTE = 'PUSH_ROUTE'; function toggleVisibility(node) { return { type: TOGGLE_VISIBILITY, node }; } function setProperty(node, path, value) { return { type: SET_PROPERTY, node, path, value }; } function setFocus(node) { return { type: SET_FOCUS, node }; } function pushRoute(route) { return { type: PUSH_ROUTE, value: route }; } function clearFocus() { return { type: CLEAR_FOCUS } } function setSearch(value) { return { type: SEARCH, value } } function side_menu(field, state) { let type = 'SIDE_MENU_OFF' if (state == true) { type = 'SIDE_MENU_ON' } return { type } } /***** Reducers *****/ function createTestDoc() { return Parser.parse( '* DONE [#A] 1. I did this :project:\nSCHEDULED: <2016-06-05 Sun>\n:LOGBOOK:\nCLOCK: [2016-06-03 Fri 18:00]--[2016-06-03 Fri 19:30] => 1:30\n- I did MORE of it\nCLOCK: [2016-06-02 Thu 18:00]--[2016-06-02 Thu 19:00] => 1:00\n- I did part of it!\n:END:\n** 1.1 Look at all\n** 1.2 Of these headlines\n*** 1.2.1 Wow such hierarchy\n**** TODO 1.2.1.1 much test\n* 2. Work :work:\n** TODO [#A] 2.1 Do this or you lose your job!\nSCHEDULED: <2016-06-04 Sat> DEADLINE: <2016-06-06 Mon>\n*** 2.1.1 You should probably\n** TODO 2.2 so many things to do\n** TODO 2.3 and so little time\nSCHEDULED: <2016-06-06 Mon>\n** TODO 2.4 to do them all\n** DONE 2.5 Except this one. You did this one.\n** DONE 2.6 important tasks\nCLOSED: [2016-06-03 Fri 14:59]\n* 3. Home :home:\n** TODO 3.1 Remember garbage day?\nSCHEDULED: <2016-06-16 Thu +1w>\n:PROPERTIES:\n:LAST_REPEAT: [2016-06-03 Fri 21:32]\n:END:\n:LOGBOOK:\n- State \"DONE\" from \"TODO\" [2016-06-03 Fri 21:32]\n:END:\n** TODO 3.2 You should go to that thing\nSCHEDULED: <2016-06-13 Mon 20:00>\n*** DONE 3.2.1 Wow go buy some gifts or something \nDEADLINE: <2016-06-12 Sun> CLOSED: [2016-06-11 Sat 21:33]\n* 4. hobbies\n** 4.1 hobby #1\n*** TODO 4.1.1 Things and stuff hobby #1\n** 4.2 hobby #2\n*** TODO 4.2.1 Things and stuff hobby #2\n** 4.3 hobby #3\n*** TODO 4.3.1 Things and stuff hobby #3\n** 4.4 hobby #4\n*** TODO 4.4.1 Things and stuff hobby #4\n**** TODO this one has lots of nesting\n***** TODO and many children\n***** TODO to make the tree traversal complex\n***** TODO Although not all tasks are TODO here\n***** DONE Like this one. This one is done' ); } export function orgAction(state=createTestDoc(), action) { let updated; switch (action.type) { case TOGGLE_VISIBILITY: let current = isHidden(action.node) updated = Org.setMeta(action.node, 'hidden', !current); return Org.getDoc(updated); case SET_PROPERTY: updated = action.node.setIn(action.path, action.value); return Org.getDoc(updated); default: return state; } } export function focusReducer(state=null, action) { switch (action.type) { case CLEAR_FOCUS: return null; case SET_FOCUS: let node = action.node; if (Org.isSection(node)) { node = Org.getParent(node); } return Org.getPath(node); default: return state; } } export function searchReducer(state='k.eq.TODO', action) { switch (action.type) { case SEARCH: return action.value default: return state } } export function toggleSideMenuReducer(state=false, action) { switch (action.type) { case 'SIDE_MENU_ON': return true case 'SIDE_MENU_OFF': return false } return state } export function createNavReducer(navReducer) { // TODO(ddohan): This feels hacky return (state, action) => { if (state) { let navigatorUID = state.currentNavigatorUID; switch (action.type) { case SET_FOCUS: route = Router.getRoute('edit_node') action = NavigationActions.push(navigatorUID, route) break case CLEAR_FOCUS: action = NavigationActions.pop(navigatorUID) break case PUSH_ROUTE: action = NavigationActions.push(navigatorUID, Router.getRoute(action.value)) break } } state = navReducer(state, action) return state; } } /***** Org helpers *****/ function isHidden(node) { return !!Org.getMeta(node, 'hidden'); } function tagsAsText(node) { tags = Org.getMeta(node, 'tags') return Array.from(tags).join(' ') } function tagsFromText(text) { let tags = text.split(''); return tags.filter(x => x.length > 0); } function getKeyword(node) { return Org.getMeta(node, 'keyword'); } function dateToRelativeText(then) { return Moment([then.year, then.month - 1, then.day]).fromNow(); } /**********************/ /***** Components *****/ /**********************/ let noop = () => {}; /*** Editable Fields ***/ function EditNodePath({ node, path, onChangeText=noop, onEndEditing=noop, onSubmitEditing=noop, multiline=false, style=[] }) { return ( <TextInput multiline={multiline} onChangeText={(text) => onChangeText(node, path, text)} onEndEditing={() => onEndEditing(node)} onSubmitEditing={() => onSubmitEditing(node)} value={node.getIn(path)} autoFocus={true} underlineColorAndroid={'transparent'} style={[styles.flex, ...style]}/> ); } EditNodePath = connect(() => ({}), (dispatch) => ({ onChangeText: (node, path, text) => dispatch(setProperty(node, path, text)), }))(EditNodePath); let EditNodeContent = connect(() => ({}), (dispatch) => ({ onChangeText: (node, path, text) => dispatch(setProperty(node, path, text)), onEndEditing: (node) => dispatch(setProperty(node, ['meta', 'editing'], false)), onSubmitEditing: (node) => dispatch(setProperty(node, ['meta', 'editing'], false)) }))(EditNodePath); /*** Fields ***/ function NodePath({ node, path, onPress, onLongPress }) { return ( <TouchableHighlight onPress={() => onPress(node)} onLongPress={() => onLongPress(node)}> <View> <Text style={styles.flex}> {node.getIn(path)} </Text> </View> </TouchableHighlight> ); } NodePath = connect((state) => ({}), (dispatch) => ({ onPress: (node) => dispatch(setProperty(node, ['meta', 'editing'], true)), onLongPress: (node) => dispatch(setFocus(node)) }))(NodePath); function Node({ node }) { let isSection = Org.isSection(node); let nodeButton = isSection ? null : (<CollapseNodeButton node={node}/>); let nodeContent; if (!!Org.getMeta(node, 'editing')) { nodeContent = <EditNodeContent node={node} path={['content']} multiline={isSection}/>; } else { nodeContent = <NodePath node={node} path={['content']}/>; } let keyword = getKeyword(node); return ( <View> <View style={{flexDirection: 'row'}}> {nodeButton} <Keyword keyword={keyword} /> {nodeContent} </View> <View style={styles.children}> <Children node={node}/> </View> </View>); } function TODO() { return ( <Text style={{color: 'red'}}> TODO </Text> ); } function DONE() { return ( <Text style={{color: 'green'}}> DONE </Text> ) } function Keyword({ keyword }) { if (keyword == null) { return <View />; } else if (keyword === 'TODO') { return <TODO/>; } else if (keyword === 'DONE') { return <DONE/>; } else { return <Text style={{color: 'blue'}}> {keyword} </Text>; } } function PropertyDropdown(property, values) { let options = []; let key = 0 for (let [label, value] of Object.entries(values)) { options.push(<Picker.Item label={label} value={value} key={key}/>); key += 1; } let dropdown = ( {node, onValueChange} ) => { return (<Picker selectedValue={Org.getMeta(node, property)} onValueChange={(value) => onValueChange(node, value)} style={styles.flex}> {options} </Picker>) } return connect(() => ({}), (dispatch) => ({ onValueChange: (node, value) => dispatch(setProperty(node, ['meta', property], value)) }))(dropdown); } let KeywordDropdown = PropertyDropdown('keyword', { '-': '-', 'TODO': 'TODO', 'DONE': 'DONE' }); let PriorityDropdown = PropertyDropdown('priority', { '-': '-', '#A': 'A', '#B': 'B', '#C': 'C' }); /*** outline view ***/ function NodeButton({ node, onPress }) { if (Org.numChildren(node) == 0) { return <Entypo name="dot-single" size={16} color="black" /> } let text = ' - '; if (isHidden(node)) { icon = <MaterialIcons name="play-circle-filled" size={20} color="black" /> } else { icon = <MaterialIcons name="arrow-drop-down-circle" size={20} color="black" /> } return ( <TouchableHighlight onPress={() => onPress(node)}> {icon} </TouchableHighlight>); } let CollapseNodeButton = connect(() => ({}), (dispatch) => ({ onPress: (node) => dispatch(toggleVisibility(node)) }))(NodeButton); function Children({ node }) { if (isHidden(node)) { return <View/> } let nodes = []; node = Org.getChild(node, 0); let i = 0; while (node !== undefined) { nodes.push({node: node, key: i}); node = Org.nextSibling(node); i += 1; } return (<View> { nodes.map(({node, key}) => (<Node node={node} key={key} />)) } </View>); } function TodoRender({ root, searchStr, setState }) { filtered = Org.search(root, searchStr); sorted = Org.sort(filtered, 'pl', (a, b) => { let as = a ? a.get('SCHEDULED') : null; let ad = a ? a.get('DEADLINE') : null; let bs = b ? b.get('SCHEDULED') : null; let bd = b ? b.get('DEADLINE') : null; cmp = Org.tsComparator; // TODO: cleanup [amin, amax] = cmp(as, ad) < 0 ? [as, ad] : [ad, as]; [bmin, bmax] = cmp(bs, bd) < 0 ? [bs, bd] : [bd, bs]; [amin, amax] = amin != null ? [amin, amax] : [amax, null]; [bmin, bmax] = bmin != null ? [bmin, bmax] : [bmax, null]; /* * Sort by minimum non-null timestamp, break ties with max */ let ret = cmp(amin, bmin); if (ret == 0) { ret = cmp(amax, bmax); } return ret } ); if (sorted.length == 0) { sorted = [null] } let datasource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) let cloned = datasource.cloneWithRows(sorted); let dates = (node) => { let planning = node.getIn(['meta', 'planning']); if (planning == null) { return <Text /> } let dates = [] for (type of ['SCHEDULED', 'DEADLINE', 'CLOSED']) { if (planning.has(type)) { dates.push( <Text key={type}> {type[0]}: {dateToRelativeText(planning.get(type))} </Text> ); } } return ( <View> {dates} </View>); } // TODO(mgyucht): use a real state machine defined by #+TODO_HEADINGS if provided let getSwipeConfiguration = (node) => { if (getKeyword(node) === 'TODO') { return { buttonTitle: 'Done', nextState: 'DONE', }; } else { return { buttonTitle: 'Todo', nextState: 'TODO', } } }; return ( <ListView dataSource={cloned} renderRow={(node) => { const swipeConfig = getSwipeConfiguration(node); const swipeoutButtons = [ { text: swipeConfig.buttonTitle, backgroundColor: 'green', underlayColor: 'rgba(0, 0, 0, 1, 0.6)', onPress: () => {setState(node, swipeConfig.nextState)}, }, ]; if (node == null) { return <Text>No search result</Text> } return <View> <Swipeout right={swipeoutButtons} autoClose={true}> <View style={[styles.row]}> <Keyword keyword={getKeyword(node)}/> <Text> {Org.getContent(node)} </Text> </View> {dates(node)} </Swipeout> </View>}} renderSeparator={(sectionID, rowID) => (<View key={`${sectionID}-${rowID}`} style={styles.separator} />)} /> ); } TodoRender = connect((state) => ({ root: state.doc }), (dispatch) => ({setState: (node, newState) => dispatch(setProperty(node, ['meta', 'keyword'], newState))}))(TodoRender); /*** Edit node view ***/ function OrgSearchBar({searchStr, onFocus, onTextChange}) { return <SearchBar round={true} value={searchStr} onChangeText={onTextChange} onFocus={onFocus} lightTheme={true} inputStyle={{width: 250}} /> } OrgSearchBarFocus = connect((state) => ({searchStr: state.search}), (dispatch) => ({ onFocus: () => dispatch(pushRoute('search')), onTextChange: (value) => dispatch(setSearch(value)) }))(OrgSearchBar) // TODO(ddohan): How to dedup with above? OrgSearchBarNoFocus = connect((state) => ({searchStr: state.search}), (dispatch) => ({ onTextChange: (value) => dispatch(setSearch(value)) }))(OrgSearchBar) function MenuDropdown() { return ( <View style={{ padding: 15, flexDirection: 'row', backgroundColor: 'white' }}> <Menu onSelect={(value) => alert(`User selected the number ${value}`)}> <MenuTrigger> <Text style={{ fontSize: 20 }}>&#8942;</Text> </MenuTrigger> <MenuOptions> <MenuOption value={1}> <Text>One</Text> </MenuOption> <MenuOption value={2}> <Text>Two</Text> </MenuOption> </MenuOptions> </Menu> </View>) } /*** Entry points ***/ @withNavigation @connect(data => OutlineView.getDataProps) export class OutlineView extends Component { static getDataProps(data) { return { doc: data.doc, }; }; static route = { navigationBar: { title: 'Outline', renderRight: () => <MenuDropdown/> }, } // <TodoSideMenu/> render() { return (<View style={styles.tree}> <Children node={this.props.doc} /> </View>) } onPressBack = () => { try { this.props.navigator.pop() } catch (e) {} } } @withNavigation @connect(data => EditView.getDataProps) export class EditView extends Component { static getDataProps(data) { return { doc: data.doc, focus: data.focus, }; }; static route = { navigationBar: { title: 'Edit Headline', }, } render() { let node = Org.createCursor(this.props.doc, this.props.focus); let child = Org.getChild(node, 0); if (!!child && Org.isSection(child)) { child = <EditNodePath node={child} path={['content']} multiline={true}/> } else { child = <View/> } return ( <View> <EditNodePath node={node} path={['content']} /> <View style={styles.row}> <Text> Priority: </Text> <PriorityDropdown node={node} /> </View> <View style={styles.row}> <Text> Keyword: </Text> <KeywordDropdown node={node} /> </View> <Text> {tagsAsText(node)} </Text> {child} </View> ) } /* onPressBack = () => { * try { * this.props.navigator.pop() * } catch (e) {} * }*/ } @withNavigation @connect(data => SearchView.getDataProps) export class SearchView extends Component { static getDataProps(data) { return { doc: data.doc, focus: data.focus, searchStr: data.search }; }; static route = { navigationBar: { title: 'Search', renderRight: () => <OrgSearchBarNoFocus/> }, } render() { return <TodoRender searchStr={this.props.searchStr} />; } onPressBack = () => { try { this.props.navigator.pop(); } catch (e) {} } } // Treat the DrawerNavigationLayout route like any other route -- you may want to set // it as the intiial route for a top-level StackNavigation onTextChange: (value) => dispatch(setSearch(value)) @connect(data => DrawerNavigationLayout.getDataProps, dispatch => DrawerNavigationLayout.getDispatch) export class DrawerNavigationLayout extends React.Component { static getDataProps(data) { return { doc: data.search, }; }; static getDispatch(dispatch) { return { dispatch: dispatch }; }; static route = { navigationBar: { visible: false, } }; render() { return ( <DrawerNavigation id='main' initialItem='outline' drawerWidth={300} renderHeader={this._renderHeader} > <DrawerNavigationItem renderTitle={() => <OrgSearchBarNoFocus/>} > </DrawerNavigationItem> <DrawerNavigationItem id='outline' selectedStyle={styles.selectedItemStyle} onPress={() => this.props.dispatch(pushRoute('outline'))} renderTitle={isSelected => this._renderTitle('Outline', isSelected)} > <StackNavigation id='outline' initialRoute={Router.getRoute('outline')} /> </DrawerNavigationItem> <DrawerNavigationItem id='todo' selectedStyle={styles.selectedItemStyle} onPress={() => {this.props.dispatch(setSearch('k.eq.TODO')); this.props.dispatch(pushRoute('search'))}} renderTitle={isSelected => this._renderTitle('Todo', isSelected)} > <StackNavigation id='search' initialRoute={Router.getRoute('search')} /> </DrawerNavigationItem> <DrawerNavigationItem id='done' selectedStyle={styles.selectedItemStyle} onPress={() => {this.props.dispatch(setSearch('k.eq.DONE')); this.props.dispatch(pushRoute('search'))}} renderTitle={isSelected => this._renderTitle('Done', isSelected)} > <StackNavigation id='search' initialRoute={Router.getRoute('search')} /> </DrawerNavigationItem> </DrawerNavigation> ); } _renderHeader = () => { return ( <View style={styles.header}> </View> ); }; _renderTitle(text: string, isSelected: boolean) { return ( <Text style={[styles.titleText, isSelected ? styles.selectedTitleText : {}]}> {text} </Text> ); }; } // TODO(dmrd): Cleanup styles const styles = StyleSheet.create({ tree: { padding: 10 }, row: { flexDirection: 'row' }, col: { flexDirection: 'column' }, separator: { height: 1, backgroundColor: '#CCCCCC', }, children: { paddingLeft: 20 }, flex: { flex: 1 }, // From other styles. header: { height: 20 }, selectedItemStyle: { backgroundColor: 'blue' }, titleText: { fontWeight: 'bold' }, selectedTitleText: { color: 'white' } });
actor-apps/app-web/src/app/components/SidebarSection.react.js
nguyenhongson03/actor-platform
import React from 'react'; //import { Styles, Tabs, Tab } from 'material-ui'; //import ActorTheme from 'constants/ActorTheme'; import HeaderSection from 'components/sidebar/HeaderSection.react'; import RecentSection from 'components/sidebar/RecentSection.react'; //import ContactsSection from 'components/sidebar/ContactsSection.react'; //const ThemeManager = new Styles.ThemeManager(); class SidebarSection extends React.Component { //static childContextTypes = { // muiTheme: React.PropTypes.object //}; // //getChildContext() { // return { // muiTheme: ThemeManager.getCurrentTheme() // }; //} constructor(props) { super(props); //ThemeManager.setTheme(ActorTheme); } render() { return ( <aside className="sidebar"> <HeaderSection/> <RecentSection/> {/* <Tabs className="sidebar__tabs" contentContainerClassName="sidebar__tabs__tab-content" tabItemContainerClassName="sidebar__tabs__tab-items"> <Tab label="Recent"> <RecentSection/> </Tab> <Tab label="Contacts"> <ContactsSection/> </Tab> </Tabs> */} </aside> ); } } export default SidebarSection;
examples/todomvc/containers/App.js
gogobook/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createRedux } from 'redux'; import { Provider } from 'redux/react'; import * as stores from '../stores'; const redux = createRedux(stores); export default class App extends Component { render() { return ( <Provider redux={redux}> {() => <TodoApp />} </Provider> ); } }
src/parser/paladin/protection/modules/features/ShieldOfTheRighteous.js
FaideWW/WoWAnalyzer
import React from 'react'; import { formatPercentage, formatThousands } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Analyzer from 'parser/core/Analyzer'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import SPELLS from 'common/SPELLS'; import MAGIC_SCHOOLS from 'game/MAGIC_SCHOOLS'; import {findByBossId} from 'raids/index'; const SOTR_DURATION = 4500; const isGoodCast = (cast, end_time) => cast.melees >= 2 || cast.tankbusters >= 1 || cast.remainingCharges >= 1.35 || cast.buffEndTime > end_time; class ShieldOfTheRighteous extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; physicalHitsWithShieldOfTheRighteous = 0; physicalDamageWithShieldOfTheRighteous = 0; physicalHitsWithoutShieldOfTheRighteous = 0; physicalDamageWithoutShieldOfTheRighteous = 0; _tankbusters = []; _sotrCasts = [ /* { castTime: <timestamp>, buffStartTime: <timestamp>, // if extending, when the "new" buff starts. otherwise just castTime buffEndTime: <timestamp>, // end time of the buff. if the current buff is > 2x SOTR_DURATION then this can be < SOTR_DURATION melees: <number>, // melees received while during buff tankbusters: <number>, // tankbusters mitigated by buff remainingCharges: <number>, // fractional number of charges remaining *after* cast } */ ]; // this setup is used to track which melee attacks are mitigated by // which casts. _futureCasts = []; _activeCast = null; _buffExpiration = 0; constructor(...args) { super(...args); const boss = findByBossId(this.owner.boss.id); this._tankbusters = boss.fight.softMitigationChecks; } _partialCharge() { const cd = this.spellUsable._currentCooldowns[SPELLS.SHIELD_OF_THE_RIGHTEOUS.id]; return 1 - this.spellUsable.cooldownRemaining(SPELLS.SHIELD_OF_THE_RIGHTEOUS.id) / cd.expectedDuration; } on_byPlayer_cast(event) { if(event.ability.guid !== SPELLS.SHIELD_OF_THE_RIGHTEOUS.id) { return; } const buffEndTime = Math.min( // if the buff expired before the current event, its just // event.timestamp + SOTR_DURATION ... Math.max(this._buffExpiration, event.timestamp) + SOTR_DURATION, // ... otherwise limit it to no more than 3x SOTR_DURATION from // now due to buff duration caps event.timestamp + SOTR_DURATION * 3 ); const cast = { castTime: event.timestamp, buffStartTime: Math.max(this._buffExpiration, event.timestamp), buffEndTime: buffEndTime, melees: 0, tankbusters: 0, remainingCharges: this.spellUsable.chargesAvailable(SPELLS.SHIELD_OF_THE_RIGHTEOUS.id) + this._partialCharge(), _event: event, }; this._buffExpiration = buffEndTime; this._updateActiveCast(event); if(cast.buffStartTime > cast.castTime) { this._futureCasts.push(cast); } else { this._activeCast = cast; } this._sotrCasts.push(cast); } on_toPlayer_damage(event) { if(event.ability.type !== MAGIC_SCHOOLS.ids.PHYSICAL) { return; } if (this.selectedCombatant.hasBuff(SPELLS.SHIELD_OF_THE_RIGHTEOUS_BUFF.id)) { this.physicalHitsWithShieldOfTheRighteous += 1; this.physicalDamageWithShieldOfTheRighteous += event.amount + (event.absorbed || 0) + (event.overkill || 0); if(this._tankbusters.includes(event.ability.guid)) { this._processTankbuster(event); } else { this._processPhysicalHit(event); } } else { this.physicalHitsWithoutShieldOfTheRighteous += 1; this.physicalDamageWithoutShieldOfTheRighteous += event.amount + (event.absorbed || 0) + (event.overkill || 0); } } on_finished(event) { if(this._activeCast) { this._markupCast(this._activeCast); } this._futureCasts.forEach(this._markupCast.bind(this)); } _processPhysicalHit(event) { this._updateActiveCast(event); if(!this._activeCast) { return; } this._activeCast.melees += 1; } _processTankbuster(event) { this._updateActiveCast(event); if(!this._activeCast) { return; } this._activeCast.tankbusters += 1; } // if the buff associated with the current active cast is no longer // active, move to the next. _updateActiveCast(event) { while(this._activeCast && this._activeCast.buffEndTime < event.timestamp) { this._markupCast(this._activeCast); this._activeCast = this._futureCasts.shift(); } } _markupCast(cast) { if(isGoodCast(cast, this.owner.fight.end_time)) { return; } const meta = cast._event.meta || {}; meta.isInefficientCast = true; meta.inefficientCastReason = 'This cast did not block many melee attacks, or block a tankbuster, or prevent you from capping SotR charges.'; cast._event.meta = meta; } get goodCasts() { return this._sotrCasts.filter(cast => isGoodCast(cast, this.owner.fight.end_time)); } get suggestionThresholds() { return { actual: this.goodCasts.length / this._sotrCasts.length, isLessThan: { minor: 0.9, average: 0.75, major: 0.6, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>{formatPercentage(actual)}% of your <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> casts were <em>good</em> (they mitigated at least 2 auto-attacks or 1 tankbuster, or prevented capping charges). You should have Shield of the Righteous up to mitigate as much physical damage as possible.</>) .icon(SPELLS.SHIELD_OF_THE_RIGHTEOUS.icon) .actual(`${formatPercentage(actual)}% good Shield of the Righteous casts`) .recommended(`${Math.round(formatPercentage(recommended))}% or more is recommended`); }); } statistic() { const physicalHitsMitigatedPercent = this.physicalHitsWithShieldOfTheRighteous / (this.physicalHitsWithShieldOfTheRighteous + this.physicalHitsWithoutShieldOfTheRighteous); const physicalDamageMitigatedPercent = this.physicalDamageWithShieldOfTheRighteous / (this.physicalDamageWithShieldOfTheRighteous + this.physicalDamageWithoutShieldOfTheRighteous); return ( <StatisticBox icon={<SpellIcon id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} />} value={`${formatPercentage (physicalDamageMitigatedPercent)}%`} label="Physical damage mitigated" tooltip={`Shield of the Righteous usage breakdown: <ul> <li>You were hit <b>${this.physicalHitsWithShieldOfTheRighteous}</b> times with your Shield of the Righteous buff (<b>${formatThousands(this.physicalDamageWithShieldOfTheRighteous)}</b> damage).</li> <li>You were hit <b>${this.physicalHitsWithoutShieldOfTheRighteous}</b> times <b><i>without</i></b> your Shield of the Righteous buff (<b>${formatThousands(this.physicalDamageWithoutShieldOfTheRighteous)}</b> damage).</li> </ul> <b>${formatPercentage(physicalHitsMitigatedPercent)}%</b> of physical attacks were mitigated with Shield of the Righteous (<b>${formatPercentage(physicalDamageMitigatedPercent)}%</b> of physical damage taken).<br/> <b>${this.goodCasts.length}</b> of your ${this._sotrCasts.length} casts were <em>good</em> (blocked at least 2 melees or a tankbuster, or prevented capping charges).`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(10); } export default ShieldOfTheRighteous;
react-flux-mui/js/material-ui/src/svg-icons/editor/insert-comment.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertComment = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/> </SvgIcon> ); EditorInsertComment = pure(EditorInsertComment); EditorInsertComment.displayName = 'EditorInsertComment'; EditorInsertComment.muiName = 'SvgIcon'; export default EditorInsertComment;
src/scripts/components/dropdown/Dropdown.component.js
kodokojo/kodokojo-ui-commons
/** * Kodo Kojo - Software factory done right * Copyright © 2017 Kodo Kojo (infos@kodokojo.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import { themr } from 'react-css-themr' // UI library component import { dropdownFactory as toolboxDropdownFactory } from 'react-toolbox/lib/dropdown/Dropdown' // component import { DROPDOWN } from '../../commons/identifiers' import '../../../styles/_commons.less' import dropdownTheme from './dropdown.scss' import Input from '../input/Input.component' /** * UI: Dropdown component * */ const Dropdown = toolboxDropdownFactory(Input) export default themr(DROPDOWN, dropdownTheme)(Dropdown)
src/components/Home/HomePage.js
AKaudinov/ReactReduxStarterKit
import React from 'react'; //There are some limitations to hot-reloading, stateless function components don't //hot-reload unless they have a parent class based component //which is why HomePage is a class based component class HomePage extends React.Component { render() { return ( <div className="home-page-main"> <div className="jumbotron"> <h1 className="home-jumbo-heading">Welcome!</h1> <p className="lead">This is the React Redux Starter kit, you can use this starter kit to begin your adventures with React, Redux, Bootstrap 4, Webpack 2, and React-Router! </p> </div> </div> ); } } export default HomePage;
src/index.js
LucasCaixeta/ReduxSimpleStarter_2
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
src/components/App.js
mleonard87/chapp-client
import { connect } from 'react-redux'; import { pushState } from 'redux-router'; import React from 'react'; import {fromJS, List, Map} from 'immutable'; export const App = React.createClass({ render: function() { return this.props.children; } }); connect( // Use a selector to subscribe to state state => (new Map({ q: state.router.location.query.q })), // Use an action creator for navigation { pushState } )(App); export default App;
examples/counter/containers/CounterApp.js
gxbsst/redux
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'redux/react'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; @connect(state => ({ counter: state.counter })) export default class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } }
Examples/UIExplorer/js/ActivityIndicatorExample.js
aaron-goshine/react-native
/** * Copyright (c) 2013-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. * * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @flow */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
app/javascript/mastodon/components/video_player.js
pfm-eyesightjp/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { isIOS } from '../is_mobile'; const messages = defineMessages({ toggle_sound: { id: 'video_player.toggle_sound', defaultMessage: 'Toggle sound' }, toggle_visible: { id: 'video_player.toggle_visible', defaultMessage: 'Toggle visibility' }, expand_video: { id: 'video_player.expand', defaultMessage: 'Expand video' }, }); @injectIntl export default class VideoPlayer extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { media: ImmutablePropTypes.map.isRequired, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, intl: PropTypes.object.isRequired, autoplay: PropTypes.bool, onOpenVideo: PropTypes.func.isRequired, }; static defaultProps = { width: 239, height: 110, }; state = { visible: !this.props.sensitive, preview: true, muted: true, hasAudio: true, videoError: false, }; handleClick = () => { this.setState({ muted: !this.state.muted }); } handleVideoClick = (e) => { e.stopPropagation(); const node = this.video; if (node.paused) { node.play(); } else { node.pause(); } } handleOpen = () => { this.setState({ preview: !this.state.preview }); } handleVisibility = () => { this.setState({ visible: !this.state.visible, preview: true, }); } handleExpand = () => { this.video.pause(); this.props.onOpenVideo(this.props.media, this.video.currentTime); } setRef = (c) => { this.video = c; } handleLoadedData = () => { if (('WebkitAppearance' in document.documentElement.style && this.video.audioTracks.length === 0) || this.video.mozHasAudio === false) { this.setState({ hasAudio: false }); } } handleVideoError = () => { this.setState({ videoError: true }); } componentDidMount () { if (!this.video) { return; } this.video.addEventListener('loadeddata', this.handleLoadedData); this.video.addEventListener('error', this.handleVideoError); } componentDidUpdate () { if (!this.video) { return; } this.video.addEventListener('loadeddata', this.handleLoadedData); this.video.addEventListener('error', this.handleVideoError); } componentWillUnmount () { if (!this.video) { return; } this.video.removeEventListener('loadeddata', this.handleLoadedData); this.video.removeEventListener('error', this.handleVideoError); } render () { const { media, intl, width, height, sensitive, autoplay } = this.props; let spoilerButton = ( <div className={`status__video-player-spoiler ${this.state.visible ? 'status__video-player-spoiler--visible' : ''}`}> <IconButton overlay title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} onClick={this.handleVisibility} /> </div> ); let expandButton = ''; if (this.context.router) { expandButton = ( <div className='status__video-player-expand'> <IconButton overlay title={intl.formatMessage(messages.expand_video)} icon='expand' onClick={this.handleExpand} /> </div> ); } let muteButton = ''; if (this.state.hasAudio) { muteButton = ( <div className='status__video-player-mute'> <IconButton overlay title={intl.formatMessage(messages.toggle_sound)} icon={this.state.muted ? 'volume-off' : 'volume-up'} onClick={this.handleClick} /> </div> ); } if (!this.state.visible) { if (sensitive) { return ( <button style={{ width: `${width}px`, height: `${height}px`, marginTop: '8px' }} className='media-spoiler' onClick={this.handleVisibility}> {spoilerButton} <span className='media-spoiler__warning'><FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /></span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> ); } else { return ( <button style={{ width: `${width}px`, height: `${height}px`, marginTop: '8px' }} className='media-spoiler' onClick={this.handleVisibility}> {spoilerButton} <span className='media-spoiler__warning'><FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' /></span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </button> ); } } if (this.state.preview && !autoplay) { return ( <button className='media-spoiler-video' style={{ width: `${width}px`, height: `${height}px`, backgroundImage: `url(${media.get('preview_url')})` }} onClick={this.handleOpen}> {spoilerButton} <div className='media-spoiler-video-play-icon'><i className='fa fa-play' /></div> </button> ); } if (this.state.videoError) { return ( <div style={{ width: `${width}px`, height: `${height}px` }} className='video-error-cover' > <span className='media-spoiler__warning'><FormattedMessage id='video_player.video_error' defaultMessage='Video could not be played' /></span> </div> ); } return ( <div className='status__video-player' style={{ width: `${width}px`, height: `${height}px` }}> {spoilerButton} {muteButton} {expandButton} <video className='status__video-player-video' role='button' tabIndex='0' ref={this.setRef} src={media.get('url')} autoPlay={!isIOS()} loop muted={this.state.muted} onClick={this.handleVideoClick} /> </div> ); } }
app/containers/Profile/ConfirmModal.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Formsy from 'formsy-react'; import FRC from 'formsy-react-components'; import { toggleModal, enableSubmitForm, disableSubmitForm, confirmCurrentPwd } from '../../actions'; import { Modal } from '../../components/Modal'; const { Input } = FRC; class ConfirmPasswordScreen extends Component { constructor() { super(); this.submitForm = this.submitForm.bind(this); } submitForm() { const myform = this.myform.getModel(); this.props.confirmCurrentPwd(myform.password); } render() { return ( <Modal title="Current Password" contentLabel="Current Password" isOpen={this.props.isOpen} onCloseModal={() => { this.props.toggleModal('changeConfirmModal'); }} canSubmit={this.props.canSubmit} submitForm={this.submitForm} submitBtnLabel="Continue" cancelBtnLabel="Cancel" > <Formsy.Form onValidSubmit={this.submitForm} onValid={this.props.enableSubmitForm} onInvalid={this.props.disableSubmitForm} ref={(ref) => { this.myform = ref; }} > <Input name="password" id="password" help="Please enter your current password and press continue" type="password" label="Password" required /> </Formsy.Form> </Modal> ); } } ConfirmPasswordScreen.propTypes = { isOpen: PropTypes.bool, canSubmit: PropTypes.bool, toggleModal: PropTypes.func, confirmCurrentPwd: PropTypes.func, enableSubmitForm: PropTypes.func, disableSubmitForm: PropTypes.func, }; const mapStateToProps = (state) => { return { isOpen: state.modal.changeConfirmModal, canSubmit: state.appstate.enableSubmitForm, }; }; const ConfirmPassword = connect(mapStateToProps, { toggleModal, enableSubmitForm, disableSubmitForm, confirmCurrentPwd, })(ConfirmPasswordScreen); export { ConfirmPassword };
generators/react/templates/src/services/i18n/create-component-with-intl.js
theodo/theodo-stack-generator
// @flow import React from 'react'; import renderer from 'react-test-renderer'; import { IntlProvider } from 'react-intl'; import frMessages from 'translations/fr.json'; import { flattenMessages } from './intl'; type IntlProps = { locale: string, messages: { [string]: string }, }; const locales = { fr: flattenMessages(frMessages), }; const createComponentWithIntl = ( children: React$Element<*>, props: IntlProps = { locale: 'fr', messages: locales.fr }, ) => renderer.create(<IntlProvider {...props}>{children}</IntlProvider>); export default createComponentWithIntl;
ui/src/stories/Spinner.stories.js
damianmoore/photo-manager
import React from 'react' import Spinner from '../components/Spinner' export default { title: 'Photonix/Misc/Spinner', component: Spinner, } const Template = (args) => ( <div style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', }} > <Spinner {...args} /> </div> ) export const DefaultSpinner = Template.bind({})
src/icons/MusicNote.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class MusicNote extends React.Component { render() { if(this.props.bare) { return <g> <path d="M426,32.1c-2.2,0-5.1,0.6-5.1,0.6L203.3,65.9C189.5,69.6,177,83,176,97.5V384h-61v-0.1c-28,0-51.1,20-51.1,48 s23.1,48,51.3,48h36.2c15.3,0,28.9-6.9,38.3-17.5c0.1-0.1,0.3-0.1,0.4-0.2c0.6-0.6,1-1.5,1.5-2.1c1.3-1.6,2.4-3.2,3.4-5 C204.6,441,208,422.3,208,414V182l208-38c0,0,0,136,0,192h-60.5c-28.3,0-51.2,19.9-51.2,48s22.9,48,51.2,48h37.2 c18.2,0,34.1-6,43.2-21c0,0,0.1,0,0.2,0c9-12,12-30.2,12-54.9c0-24.8,0-302.8,0-302.8C448,41.6,438.1,32.1,426,32.1z"></path> </g>; } return <IconBase> <path d="M426,32.1c-2.2,0-5.1,0.6-5.1,0.6L203.3,65.9C189.5,69.6,177,83,176,97.5V384h-61v-0.1c-28,0-51.1,20-51.1,48 s23.1,48,51.3,48h36.2c15.3,0,28.9-6.9,38.3-17.5c0.1-0.1,0.3-0.1,0.4-0.2c0.6-0.6,1-1.5,1.5-2.1c1.3-1.6,2.4-3.2,3.4-5 C204.6,441,208,422.3,208,414V182l208-38c0,0,0,136,0,192h-60.5c-28.3,0-51.2,19.9-51.2,48s22.9,48,51.2,48h37.2 c18.2,0,34.1-6,43.2-21c0,0,0.1,0,0.2,0c9-12,12-30.2,12-54.9c0-24.8,0-302.8,0-302.8C448,41.6,438.1,32.1,426,32.1z"></path> </IconBase>; } };MusicNote.defaultProps = {bare: false}
src/transition/app.js
SodhanaLibrary/react-examples
import React from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; class App extends React.Component { constructor(props) { super(props); this.state = { items: ['Item 1...', 'Item 2...', 'Item 3...', 'Item 4...'] } this.handleAdd = this.handleAdd.bind(this); } handleAdd() { var newItems = this.state.items.concat([prompt('Create New Item')]); this.setState({items: newItems}); } handleRemove(i) { var newItems = this.state.items.slice(); newItems.splice(i, 1); this.setState({items: newItems}); } render() { var items = this.state.items.map(function(item, i) { return ( <div key = {item} onClick = {this.handleRemove.bind(this, i)}> {item} </div> ); }.bind(this)); return ( <div> <button onClick = {this.handleAdd}>Add Item</button> <ReactCSSTransitionGroup transitionName = "example" transitionEnterTimeout = {5000} transitionLeaveTimeout = {5000}> {items} </ReactCSSTransitionGroup> </div> ); } } export default App;
app/components/Logo/index.js
acebusters/ab-web
import React from 'react'; import styled from 'styled-components'; import { baseColor, white, } from '../../variables'; export const LogoContainer = styled.div` width: 40px; height: 40px; box-sizing: content-box; `; export const NameContainer = styled.div` font-size: 20px; font-weight: bold; `; // eslint-disable-start export const Logo = (props) => ( <svg viewBox="0 0 416 50" width="217" height="26" xmlns="http://www.w3.org/2000/svg" {...props}> <g fill="#FFF" fillRule="evenodd"> <path d="M75.36 40.535L68.84 28.06l-6.287 12.475H55L68.84 12l13.886 28.535H75.36zm39.924 0h-13.652c-3.534 0-6.677-1.32-9.43-3.957-2.752-2.638-4.128-5.974-4.128-10.008 0-3.848 1.376-7.138 4.128-9.87 2.753-2.73 5.896-4.095 9.43-4.095h13.652v6.982h-13.652c-2.095 0-3.87.69-5.325 2.072-1.454 1.38-2.18 3.01-2.18 4.91 0 1.89.726 3.53 2.18 4.91 1.455 1.38 3.23 2.07 5.325 2.07h13.652v6.98zm32.84-20.948H127.01v5.96c2.377-1.615 4.88-2.422 7.507-2.422h13.603v6.89h-13.6c-1.41 0-2.707.333-3.895 1-1.19.667-2.065 1.513-2.627 2.537h20.125v6.983h-27.21v-27.93h27.21v6.982zm32.84 1.583c0 2.08-.595 3.88-1.784 5.4 1.19 1.52 1.783 3.32 1.783 5.4 0 2.39-.798 4.414-2.393 6.074-1.595 1.66-3.518 2.49-5.77 2.49h-19.047v-27.93H172.8c2.252 0 4.175.83 5.77 2.492 1.595 1.66 2.393 3.685 2.393 6.074zm-21.112-1.583v3.817h12.62c.656 0 1.14-.186 1.454-.558.313-.372.47-.822.47-1.35 0-.528-.157-.978-.47-1.35-.313-.372-.798-.56-1.454-.56h-12.62zm0 13.965h12.62c.656 0 1.14-.186 1.454-.558.313-.373.47-.823.47-1.35 0-.528-.157-.978-.47-1.35-.313-.373-.798-.56-1.454-.56h-12.62v3.818zm53.95-20.947v14.477c0 3.662-1.297 6.897-3.893 9.705-2.6 2.81-5.84 4.213-9.72 4.213-3.72 0-6.92-1.396-9.6-4.19-2.68-2.792-4.01-6.035-4.01-9.728V12.605h6.09v14.477c0 1.893.73 3.53 2.18 4.91 1.45 1.382 3.23 2.072 5.32 2.072s3.87-.69 5.322-2.07c1.456-1.382 2.18-3.02 2.18-4.912V12.605h6.1zm31.433 6.982H227.5c-.656 0-1.148.187-1.477.56-.328.37-.492.82-.492 1.35 0 .496.17.93.5 1.302.33.37.82.57 1.48.6h11.08c2.25 0 4.16.78 5.73 2.35s2.35 3.53 2.35 5.89c0 2.45-.79 4.54-2.37 6.28-1.58 1.74-3.48 2.6-5.7 2.6h-18.21v-6.98h18.205c.655 0 1.15-.19 1.476-.56.33-.38.5-.83.5-1.35 0-.5-.174-.93-.52-1.31-.342-.38-.83-.58-1.452-.61H227.5c-2 0-3.846-.75-5.535-2.24-1.688-1.49-2.533-3.49-2.533-6.005 0-2.42.79-4.507 2.37-6.26 1.58-1.754 3.48-2.63 5.7-2.63h17.733v6.98zm23.69 20.948h-6.098v-27.93h6.1v27.93zm-6.567-20.948h-10.086v-6.935h10.086v6.935zm17.123 0H269.4v-6.935h10.086v6.935zm32.84 0h-21.11v5.96c2.38-1.615 4.88-2.422 7.51-2.422h13.61v6.89h-13.61c-1.4 0-2.7.333-3.89 1s-2.06 1.513-2.62 2.537h20.13v6.983h-27.21v-27.93h27.21v6.982zm5.63-6.982H337c2.22 0 4.136.822 5.746 2.467 1.61 1.645 2.416 3.678 2.416 6.098 0 2.855-1.063 5.12-3.19 6.796 2.033 2.36 3.097 5.29 3.19 8.798v3.77h-6.098v-3.77c0-1.893-.72-3.538-2.158-4.934-1.44-1.397-3.19-2.095-5.255-2.095h-7.6v10.8h-6.1v-27.93zm6.1 6.982v3.817h12.62c.63 0 1.11-.186 1.43-.558.33-.372.5-.822.5-1.35 0-.528-.16-.978-.49-1.35-.32-.372-.8-.56-1.43-.56h-12.62zm52.55 0h-17.74c-.65 0-1.15.187-1.48.56-.32.37-.49.82-.49 1.35 0 .496.17.93.49 1.302.33.37.83.57 1.48.6h11.07c2.26 0 4.16.78 5.73 2.35 1.57 1.57 2.35 3.53 2.35 5.89 0 2.45-.79 4.54-2.37 6.28-1.58 1.74-3.48 2.6-5.7 2.6h-18.2v-6.98h18.21c.66 0 1.15-.19 1.48-.56.33-.38.49-.83.49-1.35 0-.5-.17-.93-.51-1.31-.343-.38-.83-.58-1.453-.61h-11.07c-2.002 0-3.85-.75-5.537-2.24-1.69-1.49-2.534-3.49-2.534-6.005 0-2.42.79-4.507 2.37-6.26 1.58-1.754 3.48-2.63 5.7-2.63h17.73v6.98z" /> <g fillRule="nonzero"> <path d="M13.57 50h10.86L19 41.02" /> <path d="M18.913 6L0 35.385l10.996 8.14 8.07-5.273 7.948 5.462L38 35.19 18.913 6zm.02 5.563l4.89 7.485H14.12l4.813-7.485zm7.98 28.45l-7.794-5.355-8.01 5.22-7.05-5.22 8.42-13.082h13.01l8.47 12.958-7.05 5.478z" /> </g> <path d="M386.36 3.176c0 .625-.177 1.167-.532 1.624.355.457.532 1 .532 1.624 0 .72-.238 1.328-.714 1.827-.476.5-1.05.75-1.722.75h-5.684V.6h5.684c.672 0 1.246.25 1.722.75.476.498.714 1.107.714 1.826zm-6.3-.476v1.148h3.766c.196 0 .34-.056.434-.168.093-.112.14-.247.14-.406 0-.16-.047-.294-.14-.406-.093-.112-.238-.168-.434-.168h-3.766zm0 4.2h3.766c.196 0 .34-.056.434-.168.093-.112.14-.247.14-.406 0-.16-.047-.294-.14-.406-.093-.112-.238-.168-.434-.168h-3.766V6.9zm16.1-4.2h-6.3v1.792c.71-.485 1.456-.728 2.24-.728h4.06v2.072h-4.06c-.42 0-.807.1-1.162.3-.355.202-.616.456-.784.764h6.006V9h-8.12V.6h8.12v2.1zm9.8.546h-1.82V2.7h-1.33V9h-1.82V2.7h-1.33v.546h-1.82V.614h8.12v2.632zM413.646 9L411.7 5.248 409.824 9h-2.254L411.7.418 415.844 9h-2.198z" opacity=".598" /> </g> </svg> ); // eslint-disable-stop export const LogoName = () => ( <NameContainer> <span style={{ color: baseColor }}>ACE</span> <span style={{ color: white }}>BUSTERS</span> </NameContainer> );
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js
luwei2012/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import classNames from 'classnames'; import DialogStore from 'stores/DialogStore'; export default React.createClass({ mixins: [PureRenderMixin], getInitialState() { return { typing: null, show: false }; }, componentDidMount() { DialogStore.addTypingListener(this.onTypingChange); }, componentWillUnmount() { DialogStore.removeTypingListener(this.onTypingChange); }, onTypingChange() { const typing = DialogStore.getSelectedDialogTyping(); if (typing === null) { this.setState({show: false}); } else { this.setState({typing: typing, show: true}); } }, render() { const typing = this.state.typing; const show = this.state.show; const typingClassName = classNames('typing', { 'typing--hidden': show === false }); return ( <div className={typingClassName}> <div className="typing-indicator"><i></i><i></i><i></i></div> <span>{typing}</span> </div> ); } });
Rosa_Madeira/Revendedor/src/components/clientes/ClienteVendaLista.js
victorditadi/IQApp
import React, { Component } from 'react'; import { ScrollView, RefreshControl, ListView } from 'react-native'; import axios from 'axios'; import _ from 'lodash'; import { ButtonHome } from '../common'; import { connect } from 'react-redux'; import { fetch_cliente_venda } from '../../actions'; import ClienteVendaItem from './ClienteVendaItem'; class ClienteVendaLista extends Component { componentWillMount(){ // console.log(this.props); this.props.fetch_cliente_venda(this.props.codigo_cliente); this.createDataSource(this.props) } componentWillReceiveProps(nextProps){ // console.log("REFRESH -> "+ this.props.refreshing); this.createDataSource(nextProps) } createDataSource({listClienteVenda}) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(listClienteVenda); } renderRow(listClienteVenda) { return <ClienteVendaItem clienteVenda={listClienteVenda} /> } _onRefresh(){ setTimeout(() => { this.props.fetch_cliente_venda(this.props.codigo_cliente); }, 1000); } render() { return( <ScrollView style={{flex:1, backgroundColor: '#ede6de', marginTop: 20, marginBottom: 60}} refreshControl={ <RefreshControl refreshing={this.props.refreshing} onRefresh={this._onRefresh.bind(this)} tintColor="transparent" /> }> <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} style={{marginTop: 50}} /> </ScrollView> ); } }; const mapStateToProps = state => { // console.log(state); const listClienteVenda = _.map(state.clientes.listVendaCliente.data, (key, value) => { return { ...key, value }; }); const refreshing = state.vendas.isRefreshing; return { listClienteVenda, refreshing }; }; export default connect(mapStateToProps, {fetch_cliente_venda})(ClienteVendaLista);
src/icons/SocialSnapchatOutline.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class SocialSnapchatOutline extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M256.283,47.553c70.693,0,128,54.682,118,128.931c-2.072,15.388-3.422,31.483-4.26,44.759c0,0,2.402,4.253,12.664,4.253 c6.071,0,14.895-1.543,27.596-6.354c2.236-0.847,4.377-1.241,6.377-1.241c7.918,0,13.615,5.931,14.123,12.271 c0.426,5.31-4.564,11.199-8.371,13.009c-13.766,6.542-46.991,10.063-46.991,32.638c0,22.576,22.362,46.656,40.862,63.713 S480,360.602,480,360.602s0.283,21.57-31.717,29.097c-32,7.524-32.1,5.712-33.25,13.796c-2.133,14.979-1.535,21.378-11.248,21.378 c-1.672,0-3.651-0.19-6.002-0.558c-8.23-1.291-19.239-3.644-31.121-3.644c-11.216,0-23.21,2.097-34.379,9.161 c-23,14.549-41.283,34.114-76.283,34.114s-53-19.565-76-34.114c-11.17-7.065-23.162-9.161-34.379-9.161 c-11.88,0-22.892,2.353-31.121,3.644c-2.352,0.367-4.33,0.558-6.002,0.558c-9.71,0-9.115-6.399-11.248-21.378 c-1.151-8.084-1.25-6.27-33.25-13.795s-32-29.097-32-29.097s45.5-4.012,64-21.068c18.5-17.058,40.862-41.134,40.862-63.71 c0-22.575-33.226-26.09-46.991-32.632c-3.807-1.81-8.796-7.687-8.371-12.997c0.507-6.336,6.196-12.251,14.107-12.25 c2.004,0,4.152,0.38,6.393,1.229c12.749,4.829,21.588,6.342,27.662,6.342c10.204,0,12.598-4.273,12.598-4.273 c-0.837-13.275-2.187-29.371-4.259-44.759c-10-74.249,47.307-128.931,118-128.931l0,0 M256.283,32H256 c-41.093,0-79.215,16.208-104.591,45.341c-23.982,27.534-34.375,63.345-29.265,101.292c1.416,10.51,2.46,21.231,3.21,30.618 c-3.97-0.559-9.686-1.998-17.703-5.034c-3.965-1.502-8.017-2.295-12.043-2.295c-15.641-0.001-28.844,11.852-30.057,27.003 c-1.027,12.818,8.235,24.393,17.47,28.783c4.251,2.02,9.181,3.578,14.4,5.232c6.707,2.125,14.309,4.532,19.293,7.703 c4.147,2.639,4.147,4.168,4.147,5.182c0,8.66-6.191,24.691-35.688,51.888c-10.499,9.681-39.055,15.501-54.588,16.897l-14.572,1.311 L16,360.603c0,1.679,0.312,10.546,6.485,20.319c5.246,8.306,16.073,19.283,37.863,24.407c6.179,1.453,11.186,2.563,15.208,3.454 c2.306,0.512,4.555,1.01,6.454,1.453c0.027,0.209,0.054,0.417,0.081,0.623c0.9,7.004,1.611,12.535,4.392,17.75 c2.453,4.6,8.574,12.316,22.015,12.316c2.478,0,5.249-0.246,8.472-0.751c1.672-0.263,3.386-0.554,5.2-0.863 c7.116-1.212,15.182-2.587,23.451-2.587c10.277,0,18.732,2.188,25.846,6.688c4.531,2.867,8.892,5.972,13.509,9.26 C202.967,465.481,223.358,480,256,480c32.726,0,53.293-14.582,71.439-27.446c4.576-3.244,8.898-6.309,13.377-9.142 c7.113-4.5,15.568-6.688,25.846-6.688c8.27,0,16.334,1.375,23.449,2.586c1.814,0.311,3.529,0.602,5.202,0.864 c3.223,0.505,5.993,0.751,8.472,0.751c13.44,0,19.562-7.715,22.015-12.313c2.781-5.214,3.492-10.746,4.392-17.749 c0.027-0.208,0.055-0.418,0.082-0.629c1.898-0.441,4.148-0.941,6.455-1.452c4.023-0.892,9.029-2.001,15.206-3.454 c21.851-5.139,32.611-16.17,37.79-24.518c6.098-9.828,6.296-18.736,6.273-20.422l-0.189-14.501l-14.398-1.278 c-15.413-1.396-43.8-7.219-54.301-16.9c-16.281-15.011-35.688-36.199-35.688-51.893c0-1.014,0-2.546,4.15-5.186 c4.985-3.174,12.589-5.584,19.297-7.71c5.217-1.654,10.144-3.217,14.394-5.236c9.236-4.39,18.498-15.978,17.471-28.807 c-1.215-15.166-14.424-27.046-30.072-27.046c-4.021,0-8.068,0.76-12.027,2.259c-8.027,3.041-13.743,4.41-17.705,4.962 c0.747-9.319,1.791-20.12,3.211-30.67c5.111-37.948-5.281-73.509-29.264-101.042C335.498,48.208,297.376,32,256.283,32L256.283,32z "></path> <path d="M256,229c-20.838,0-40.604-8.29-55.657-23.343c-3.125-3.124-3.124-8.189,0-11.313c3.125-3.124,8.19-3.124,11.313,0 C223.688,206.374,239.436,213,256,213c16.387,0,32.15-6.64,44.385-18.698c3.148-3.102,8.213-3.063,11.312,0.082 c3.102,3.147,3.064,8.212-0.082,11.313C296.368,220.725,276.617,229,256,229z"></path> <ellipse cx="208" cy="152" rx="16" ry="24"></ellipse> <ellipse cx="304" cy="152" rx="16" ry="24"></ellipse> </g> </g>; } return <IconBase> <g> <path d="M256.283,47.553c70.693,0,128,54.682,118,128.931c-2.072,15.388-3.422,31.483-4.26,44.759c0,0,2.402,4.253,12.664,4.253 c6.071,0,14.895-1.543,27.596-6.354c2.236-0.847,4.377-1.241,6.377-1.241c7.918,0,13.615,5.931,14.123,12.271 c0.426,5.31-4.564,11.199-8.371,13.009c-13.766,6.542-46.991,10.063-46.991,32.638c0,22.576,22.362,46.656,40.862,63.713 S480,360.602,480,360.602s0.283,21.57-31.717,29.097c-32,7.524-32.1,5.712-33.25,13.796c-2.133,14.979-1.535,21.378-11.248,21.378 c-1.672,0-3.651-0.19-6.002-0.558c-8.23-1.291-19.239-3.644-31.121-3.644c-11.216,0-23.21,2.097-34.379,9.161 c-23,14.549-41.283,34.114-76.283,34.114s-53-19.565-76-34.114c-11.17-7.065-23.162-9.161-34.379-9.161 c-11.88,0-22.892,2.353-31.121,3.644c-2.352,0.367-4.33,0.558-6.002,0.558c-9.71,0-9.115-6.399-11.248-21.378 c-1.151-8.084-1.25-6.27-33.25-13.795s-32-29.097-32-29.097s45.5-4.012,64-21.068c18.5-17.058,40.862-41.134,40.862-63.71 c0-22.575-33.226-26.09-46.991-32.632c-3.807-1.81-8.796-7.687-8.371-12.997c0.507-6.336,6.196-12.251,14.107-12.25 c2.004,0,4.152,0.38,6.393,1.229c12.749,4.829,21.588,6.342,27.662,6.342c10.204,0,12.598-4.273,12.598-4.273 c-0.837-13.275-2.187-29.371-4.259-44.759c-10-74.249,47.307-128.931,118-128.931l0,0 M256.283,32H256 c-41.093,0-79.215,16.208-104.591,45.341c-23.982,27.534-34.375,63.345-29.265,101.292c1.416,10.51,2.46,21.231,3.21,30.618 c-3.97-0.559-9.686-1.998-17.703-5.034c-3.965-1.502-8.017-2.295-12.043-2.295c-15.641-0.001-28.844,11.852-30.057,27.003 c-1.027,12.818,8.235,24.393,17.47,28.783c4.251,2.02,9.181,3.578,14.4,5.232c6.707,2.125,14.309,4.532,19.293,7.703 c4.147,2.639,4.147,4.168,4.147,5.182c0,8.66-6.191,24.691-35.688,51.888c-10.499,9.681-39.055,15.501-54.588,16.897l-14.572,1.311 L16,360.603c0,1.679,0.312,10.546,6.485,20.319c5.246,8.306,16.073,19.283,37.863,24.407c6.179,1.453,11.186,2.563,15.208,3.454 c2.306,0.512,4.555,1.01,6.454,1.453c0.027,0.209,0.054,0.417,0.081,0.623c0.9,7.004,1.611,12.535,4.392,17.75 c2.453,4.6,8.574,12.316,22.015,12.316c2.478,0,5.249-0.246,8.472-0.751c1.672-0.263,3.386-0.554,5.2-0.863 c7.116-1.212,15.182-2.587,23.451-2.587c10.277,0,18.732,2.188,25.846,6.688c4.531,2.867,8.892,5.972,13.509,9.26 C202.967,465.481,223.358,480,256,480c32.726,0,53.293-14.582,71.439-27.446c4.576-3.244,8.898-6.309,13.377-9.142 c7.113-4.5,15.568-6.688,25.846-6.688c8.27,0,16.334,1.375,23.449,2.586c1.814,0.311,3.529,0.602,5.202,0.864 c3.223,0.505,5.993,0.751,8.472,0.751c13.44,0,19.562-7.715,22.015-12.313c2.781-5.214,3.492-10.746,4.392-17.749 c0.027-0.208,0.055-0.418,0.082-0.629c1.898-0.441,4.148-0.941,6.455-1.452c4.023-0.892,9.029-2.001,15.206-3.454 c21.851-5.139,32.611-16.17,37.79-24.518c6.098-9.828,6.296-18.736,6.273-20.422l-0.189-14.501l-14.398-1.278 c-15.413-1.396-43.8-7.219-54.301-16.9c-16.281-15.011-35.688-36.199-35.688-51.893c0-1.014,0-2.546,4.15-5.186 c4.985-3.174,12.589-5.584,19.297-7.71c5.217-1.654,10.144-3.217,14.394-5.236c9.236-4.39,18.498-15.978,17.471-28.807 c-1.215-15.166-14.424-27.046-30.072-27.046c-4.021,0-8.068,0.76-12.027,2.259c-8.027,3.041-13.743,4.41-17.705,4.962 c0.747-9.319,1.791-20.12,3.211-30.67c5.111-37.948-5.281-73.509-29.264-101.042C335.498,48.208,297.376,32,256.283,32L256.283,32z "></path> <path d="M256,229c-20.838,0-40.604-8.29-55.657-23.343c-3.125-3.124-3.124-8.189,0-11.313c3.125-3.124,8.19-3.124,11.313,0 C223.688,206.374,239.436,213,256,213c16.387,0,32.15-6.64,44.385-18.698c3.148-3.102,8.213-3.063,11.312,0.082 c3.102,3.147,3.064,8.212-0.082,11.313C296.368,220.725,276.617,229,256,229z"></path> <ellipse cx="208" cy="152" rx="16" ry="24"></ellipse> <ellipse cx="304" cy="152" rx="16" ry="24"></ellipse> </g> </IconBase>; } };SocialSnapchatOutline.defaultProps = {bare: false}
About.js
ArmWeb/bet_practice
import React from 'react'; export default class About extends React.Component{ render(){ return (<div> This is about page </div>) } }
admin/client/App/screens/List/components/ItemsTable/ItemsTableDragDrop.js
Yaska/keystone
import React from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import { Sortable } from './ItemsTableRow'; import DropZone from './ItemsTableDragDropZone'; var ItemsTableDragDrop = React.createClass({ displayName: 'ItemsTableDragDrop', propTypes: { columns: React.PropTypes.array, id: React.PropTypes.any, index: React.PropTypes.number, items: React.PropTypes.object, list: React.PropTypes.object, }, render () { return ( <tbody > {this.props.items.results.map((item, i) => { return ( <Sortable key={item.id} index={i} sortOrder={item.sortOrder || 0} id={item.id} item={item} {...this.props} /> ); })} <DropZone {...this.props} /> </tbody> ); }, }); module.exports = DragDropContext(HTML5Backend)(ItemsTableDragDrop);
src/svg-icons/action/tab-unselected.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTabUnselected = (props) => ( <SvgIcon {...props}> <path d="M1 9h2V7H1v2zm0 4h2v-2H1v2zm0-8h2V3c-1.1 0-2 .9-2 2zm8 16h2v-2H9v2zm-8-4h2v-2H1v2zm2 4v-2H1c0 1.1.9 2 2 2zM21 3h-8v6h10V5c0-1.1-.9-2-2-2zm0 14h2v-2h-2v2zM9 5h2V3H9v2zM5 21h2v-2H5v2zM5 5h2V3H5v2zm16 16c1.1 0 2-.9 2-2h-2v2zm0-8h2v-2h-2v2zm-8 8h2v-2h-2v2zm4 0h2v-2h-2v2z"/> </SvgIcon> ); ActionTabUnselected = pure(ActionTabUnselected); ActionTabUnselected.displayName = 'ActionTabUnselected'; ActionTabUnselected.muiName = 'SvgIcon'; export default ActionTabUnselected;
app/components/App.js
JoaoCnh/picto-pc
import React, { Component } from 'react'; import Nav from './layout/Nav'; import BubbleWrap from './common/BubbleWrap'; import AuthAPI from '../api/auth'; import batteryUtils from '../utils/battery'; export default class App extends Component { _logout() { this.props.logout(); return this.props.push("/auth/login"); } componentWillMount() { if (!AuthAPI.isAuthenticated()) { return this.props.push("/auth/login"); } batteryUtils.setup(this.props.batteryLevelChanged); } render() { return ( <BubbleWrap> <Nav route={this.props.location.pathname} active={this.props.app.isMenuActive} batteryLevel={this.props.app.batteryLevel} toggleMenu={this.props.toggleMenu} logout={this._logout.bind(this)} /> {this.props.children} </BubbleWrap> ); } }
packages/material-ui-icons/src/PlayCircleOutline.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let PlayCircleOutline = props => <SvgIcon {...props}> <path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.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>; PlayCircleOutline = pure(PlayCircleOutline); PlayCircleOutline.muiName = 'SvgIcon'; export default PlayCircleOutline;
app/components/ButtonAdd/index.js
Ratholien/JobReact
import React from 'react'; import PropTypes from 'prop-types'; import { FlatButton } from 'material-ui'; import ActionAndroid from 'material-ui/svg-icons/content/add'; const ButtonAdd = ({ showForm }) => ( <FlatButton icon={<ActionAndroid />} onClick={showForm} /> ); ButtonAdd.propTypes = { showForm: PropTypes.func, }; export default ButtonAdd;
test/ButtonGroup.js
GetAmbassador/react-ions
import React from 'react' import ButtonGroup from '../src/components/ButtonGroup/ButtonGroup' describe('ButtonGroup', () => { let wrapper let options = [ { value: 'option_1', label: 'Option 1' }, { value: 'option_2', label: 'Option 2' } ] it('should shallow render itself', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label"/>) expect(wrapper.hasClass('button-group')).to.equal(true) expect(wrapper.find('label')).to.have.length(1) expect(wrapper.find('ButtonToggle')).to.have.length(2) expect(wrapper.childAt(1).childAt(0).props().value).to.be.equal('option_1') expect(wrapper.childAt(1).childAt(0).props().label).to.be.equal('Option 1') expect(wrapper.childAt(1).childAt(0).props().name).to.be.equal('test-group') expect(wrapper.childAt(1).childAt(0).props().checked).to.be.equal(false) expect(wrapper.childAt(1).childAt(0).props().optClass).to.be.equal('secondary') expect(wrapper.childAt(1).childAt(0).props().disabled).to.be.equal(false) expect(wrapper.childAt(1).childAt(1).props().value).to.be.equal('option_2') expect(wrapper.childAt(1).childAt(1).props().label).to.be.equal('Option 2') expect(wrapper.childAt(1).childAt(1).props().name).to.be.equal('test-group') expect(wrapper.childAt(1).childAt(1).props().checked).to.be.equal(false) expect(wrapper.childAt(1).childAt(1).props().optClass).to.be.equal('secondary') expect(wrapper.childAt(1).childAt(1).props().disabled).to.be.equal(false) }) it('should have disabled buttons', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" disabled/>) expect(wrapper.childAt(1).childAt(0).props().disabled).to.be.equal(true) expect(wrapper.childAt(1).childAt(1).props().disabled).to.be.equal(true) }) it('should be required', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" required={true}/>) expect(wrapper.childAt(0).hasClass('asterisk')).to.be.true expect(wrapper.childAt(0).html()).to.be.equal('<span class="asterisk">*</span>') }) it('should have an option selected', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" defaultOption={0}/>) expect(wrapper.state('checkedOption')).to.equal(options[0].value) wrapper.setProps({ defaultOption: 1 }) wrapper.update() expect(wrapper.state('checkedOption')).to.equal(options[1].value) }) it('should have an extra class', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" optClass="extra-class"/>) expect(wrapper.hasClass('extra-class')).to.be.true }) it('should have buttons with specific styling', () => { wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" buttonStyle='info' defaultOption={1}/>) expect(wrapper.childAt(1).childAt(0).props().optClass).to.be.equal('secondary') expect(wrapper.childAt(1).childAt(1).props().optClass).to.be.equal('info') wrapper.setProps({ buttonStyle: 'danger' }) wrapper.update() expect(wrapper.childAt(1).childAt(0).props().optClass).to.be.equal('secondary') expect(wrapper.childAt(1).childAt(1).props().optClass).to.be.equal('danger') wrapper.setProps({ buttonStyle: '' }) wrapper.update() expect(wrapper.childAt(1).childAt(0).props().optClass).to.be.equal('secondary') expect(wrapper.childAt(1).childAt(1).props().optClass).to.be.equal('') }) it('should call changeCallback function', () => { const spy = sinon.spy() wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" changeCallback={spy}/>) wrapper.instance().handleChange({ persist: () => {} }, 'test') expect(spy.calledOnce).to.be.true }) it('should update selected value via callback', () => { let selected = false const callback = function (event, value) { selected = value } wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" changeCallback={callback}/>) const handleChange = wrapper.instance().handleChange handleChange({ persist: () => {} }, 'option_1') expect(wrapper.state('checkedOption')).to.equal('option_1') }) it('should use custom props for value and label', () => { options = [ { customValue: 'option_1', customLabel: 'Option 1' }, { customValue: 'option_2', customLabel: 'Option 2' } ] wrapper = shallow(<ButtonGroup name="test-group" options={options} label="Test label" valueProp='customValue' displayProp='customLabel' />) expect(wrapper.find('ButtonToggle').at(0).props().value).to.equal('option_1') expect(wrapper.find('ButtonToggle').at(0).props().label).to.equal('Option 1') expect(wrapper.find('ButtonToggle').at(1).props().value).to.equal('option_2') expect(wrapper.find('ButtonToggle').at(1).props().label).to.equal('Option 2') }) })
src/encoded/static/components/item-pages/QualityMetricView.js
4dn-dcic/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import memoize from 'memoize-one'; import Collapse from 'react-bootstrap/esm/Collapse'; import { console, object, schemaTransforms, valueTransforms } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import DefaultItemView, { WrapInColumn } from './DefaultItemView'; import { QCMetricFromSummary } from './../browse/components/file-tables'; import { Schemas } from './../util'; export default class QualityMetricView extends DefaultItemView { getTabViewContents() { const initTabs = []; initTabs.push(QualityMetricViewOverview.getTabObject(this.props)); return initTabs.concat(this.getCommonTabs()); // Add remainder of common tabs (Details, Attribution) } } class QualityMetricViewOverview extends React.PureComponent { static getTabObject({ context, schemas }) { return { 'tab': <span><i className="icon far icon-file-alt icon-fw" /> Overview</span>, 'key': 'quality-metric-info', 'content': ( <div className="overflow-hidden"> <h3 className="tab-section-title"> <span>More Information</span> </h3> <hr className="tab-section-title-horiz-divider" /> <div className="row overview-blocks"> <QualityMetricViewOverview context={context} schemas={schemas} /> </div> </div> ) }; } /** * Utility method to get schema field-value pairs as an array * @param {object} schemaProp - schema property * @param {object} context - Current QC Item being shown * @param {object} schemas - all schema definitions */ static getSchemaQCFieldsAsOrderedPairs(schemaProp, context, schemas) { if (!schemaProp && !context && !schemas) { return []; } let properties = schemaProp && schemaProp.type === 'object' && schemaProp.properties; if (!properties) { properties = schemaProp && schemaProp.type === 'array' && schemaProp.items && schemaProp.items.type === 'object' && schemaProp.items.properties; } //try to get properties from schemas using @type of context if (!properties && context && schemas) { const typeSchema = schemaTransforms.getSchemaForItemType(schemaTransforms.getItemType(context), schemas || null); properties = typeSchema && typeSchema.properties; } if (properties) { return _.chain(properties) .pick(function (value, key) { return typeof value.qc_order === 'number'; }) .pairs() .sortBy(function (pair) { return pair[1].qc_order; }) .value(); } return []; } constructor(props) { super(props); this.memoized = { getSchemaQCFieldsAsOrderedPairs: memoize(QualityMetricViewOverview.getSchemaQCFieldsAsOrderedPairs) }; } render() { const { schemas, context } = this.props; const tips = object.tipsFromSchema(schemas, context); //QC Metrics Summary const { quality_metric_summary } = context; const qcMetricsSummary = context.quality_metric_summary ? ( <div className="overview-list-elements-container"> {_.map(quality_metric_summary, function (qmsItem) { return <QCMetricFromSummary {...qmsItem} key={qmsItem.title} />; })} {context.url ? <QCMetricFromSummary title="Report" tooltip="Link to full quality metric report" value={ <React.Fragment> <a href={context.url} target="_blank" rel="noopener noreferrer">{valueTransforms.hrefToFilename(context.url)}</a> <i className="ml-05 icon icon-fw icon-external-link-alt text-small fas" /> </React.Fragment> } /> : null} </div> ) : null; //QC Metrics const schemaQCFieldsAsOrderedPairs = this.memoized.getSchemaQCFieldsAsOrderedPairs(null, context, schemas); const firstObjectOrArrayIdx = _.findIndex( schemaQCFieldsAsOrderedPairs, (pair) => (pair[1].type === 'object' || pair[1].type === 'array') && context[pair[0]]); const qcMetrics = schemaQCFieldsAsOrderedPairs.length > 0 ? ( <div className="overview-list-elements-container"> {_.map(schemaQCFieldsAsOrderedPairs, (pair, idx) => { const [qcSchemaFieldKey, qcSchemaFieldValue] = pair; const defaultOpen = (firstObjectOrArrayIdx === idx); return <QCMetricFromEmbed {...{ 'metric': context, schemas, tips, 'schemaItem': qcSchemaFieldValue, 'qcProperty': qcSchemaFieldKey, defaultOpen }} />; })} </div> ) : ( <em>Not Available</em> ); return ( <React.Fragment> {qcMetricsSummary ? ( <WrapInColumn wrap="col-12 col-md-9" defaultWrapClassName="col-sm-12"> <div className="inner"> <object.TooltipInfoIconContainerAuto result={null} property={null} tips={tips} elementType="h4" fallbackTitle="Summary" className="qc-section-title" /> {qcMetricsSummary} </div> </WrapInColumn>) : null} <WrapInColumn wrap="col-12 col-md-9" defaultWrapClassName="col-sm-12"> <div className="inner"> <object.TooltipInfoIconContainerAuto result={null} property={null} tips={tips} elementType="h4" fallbackTitle="All Metrics" className="qc-section-title" /> {qcMetrics} </div> </WrapInColumn> </React.Fragment> ); } } class QCMetricFromEmbed extends React.PureComponent { static percentOfTotalReads(quality_metric, field){ var numVal = object.getNestedProperty(quality_metric, field); if (numVal && typeof numVal === 'number' && quality_metric && quality_metric['Total reads']){ var percentVal = Math.round((numVal / quality_metric['Total reads']) * 100 * 1000) / 1000; var numValRounded = valueTransforms.roundLargeNumber(numVal); return ( <span className="d-inline-block" data-tip={"Percent of total reads (= " + numValRounded + ")."}>{ percentVal + '%' }</span> ); } return '-'; } constructor(props) { super(props); const { defaultOpen } = props; this.toggleOpen = _.throttle(this.toggleOpen.bind(this), 1000); this.state = { 'open': defaultOpen || false, 'closing': false }; this.memoized = { getSchemaQCFieldsAsOrderedPairs: memoize(QualityMetricViewOverview.getSchemaQCFieldsAsOrderedPairs) }; } toggleOpen(open, e){ this.setState(function(currState){ if (typeof open !== 'boolean'){ open = !currState.open; } var closing = !open && currState.open; return { open, closing }; }, ()=>{ setTimeout(()=>{ this.setState(function(currState){ if (!currState.open && currState.closing){ return { 'closing' : false }; } return null; }); }, 500); }); } render() { const { metric, qcProperty, schemaItem, schemas, fallbackTitle, tips, percent } = this.props; const { open, closing } = this.state; const { qc_order = null, title = null, description: tip = null } = schemaItem || {}; if (schemaItem && typeof qc_order !== 'number') return null; let value = metric[qcProperty]; if (typeof value === "undefined") return null; let subQCRows = null; if (qcProperty !== 'qc_list' && schemaItem && typeof schemaItem === 'object') { const pairs = this.memoized.getSchemaQCFieldsAsOrderedPairs(schemaItem, null, null); if (pairs.length > 0) { //if child qc item also has 1 child then combine them and display as a single line if (pairs.length === 1 && pairs[0][1].type !== 'object' && typeof value[pairs[0][0]] !== 'undefined') { value = pairs[0][0] + ': ' + value[pairs[0][0]]; } else { if (Array.isArray(value)) { subQCRows = _.reduce(value, function (memo, valueItem) { return memo.concat(_.map(pairs, function (pair) { return <QCMetricFromEmbed {...{ 'metric': valueItem, 'qcProperty': pair[0], schemas, 'schemaItem': pair[1], tips: pair[1].description || tips }} />; })); }, []); } else { subQCRows = _.map(pairs, function (pair) { return <QCMetricFromEmbed {...{ 'metric': value, 'qcProperty': pair[0], schemas, 'schemaItem': pair[1], tips: pair[1].description || tips }} />; }); } } } else if (schemaItem.type === 'array' && schemaItem.items && schemaItem.items && schemaItem.items.type && ['string', 'number', 'boolean'].indexOf(schemaItem.items.type) > -1) { subQCRows = _.map(value, function (val, index) { return ( <div className="overview-list-element"> <div className="row"> <div className="col-4 text-right"> <object.TooltipInfoIconContainerAuto elementType="h5" fallbackTitle={(index + 1) + "."} className="mb-0 mt-02 text-break" /> </div> <div className="col-8"> <div className="inner value"> {val} </div> </div> </div> </div> ); }); } //qc_list is a special case. we do workaround to just display links to listed QCs. } else if (qcProperty === 'qc_list') { subQCRows = _.map(value, function (qcItem, index) { const text = qcItem.value.display_title || qcItem.value.error || ''; return ( <div className="overview-list-element"> <div className="row"> <div className="col-4 text-right"> <object.TooltipInfoIconContainerAuto elementType="h5" fallbackTitle={(index + 1) + "."} className="mb-0 mt-02 text-break" /> </div> <div className="col-8"> <div className="inner value"> <a href={object.atIdFromObject(qcItem.value)}>{text}</a> </div> </div> </div> </div> ); }); } return ( <React.Fragment> {!subQCRows ? ( <div className="overview-list-element"> <div className="row"> <div className="col-4 text-right"> <object.TooltipInfoIconContainerAuto result={metric} property={qcProperty} title={title} tips={tip || tips} elementType="h5" fallbackTitle={fallbackTitle || qcProperty} schemas={schemas} className="mb-0 mt-02 text-break" /> </div> <div className="col-8"> <div className="inner value"> {percent ? QCMetricFromEmbed.percentOfTotalReads(metric, qcProperty) : Schemas.Term.toName('quality_metric.' + qcProperty, value, true)} </div> </div> </div> </div> ) : (<h5 className="qc-grouping-title" onClick={this.toggleOpen}><i className={"icon icon-fw fas mr-5 icon-" + (open ? 'minus' : 'plus')} /><span>{title || qcProperty}</span></h5>)} {subQCRows ? ( <Collapse in={open}> <div className="inner"> {(open || closing) ? subQCRows : null} </div> </Collapse> ) : null} </React.Fragment> ); } } export class QualityControlResults extends React.PureComponent { static defaultProps = { 'hideIfNoValue' : false }; /** To be deprecated (?) - still used in files view */ metricsFromEmbeddedReport(){ const { file, schemas } = this.props; const commonProps = { 'metric' : file.quality_metric, 'tips' : object.tipsFromSchema(schemas, file.quality_metric) }; return ( <div className="overview-list-elements-container"> <QCMetricFromEmbed {...commonProps} qcProperty="Total reads" fallbackTitle="Total Reads in File" /> <QCMetricFromEmbed {...commonProps} qcProperty="Total Sequences" /> <QCMetricFromEmbed {...commonProps} qcProperty="Sequence length" /> <QCMetricFromEmbed {...commonProps} qcProperty="Cis reads (>20kb)" percent /> <QCMetricFromEmbed {...commonProps} qcProperty="Short cis reads (<20kb)" percent /> <QCMetricFromEmbed {...commonProps} qcProperty="Trans reads" fallbackTitle="Trans Reads" percent /> <QCMetricFromEmbed {...commonProps} qcProperty="Sequence length" /> <QCMetricFromEmbed {...commonProps} qcProperty="overall_quality_status" fallbackTitle="Overall Quality" /> <QCMetricFromEmbed {...commonProps} qcProperty="url" fallbackTitle="Link to Report" /> </div> ); } metricsFromSummary(){ const { file } = this.props; const metric = file && file.quality_metric; const metricURL = metric && metric.url; return ( <div className="overview-list-elements-container"> { _.map(file.quality_metric.quality_metric_summary, function(qmsItem){ return <QCMetricFromSummary {...qmsItem} key={qmsItem.title} />; }) } { metricURL ? <QCMetricFromSummary title="Report" tooltip="Link to full quality metric report" value={ <React.Fragment> <a href={metricURL} target="_blank" rel="noopener noreferrer">{ valueTransforms.hrefToFilename(metricURL) }</a> <i className="ml-05 icon icon-fw icon-external-link-alt text-small fas"/> </React.Fragment> } /> : null } </div> ); } render(){ const { file, hideIfNoValue, schemas, wrapInColumn } = this.props; let metrics, titleProperty = "quality_metric_summary"; const qualityMetricEmbeddedExists = file && file.quality_metric && object.itemUtil.atId(file.quality_metric); const qualityMetricSummaryExists = file && file.quality_metric && Array.isArray(file.quality_metric.quality_metric_summary) && file.quality_metric.quality_metric_summary.length > 0; if (qualityMetricSummaryExists){ metrics = this.metricsFromSummary(); } else if (qualityMetricEmbeddedExists){ metrics = this.metricsFromEmbeddedReport(); titleProperty = "quality_metric"; } else if (hideIfNoValue){ return null; } const tips = object.tipsFromSchema(schemas, file); return ( <WrapInColumn wrap={wrapInColumn} defaultWrapClassName="col-sm-12"> <div className="inner"> <object.TooltipInfoIconContainerAuto result={file} property={titleProperty} tips={tips} elementType="h5" fallbackTitle="Quality Metric Summary" /> { metrics || (<em>Not Available</em>) } </div> </WrapInColumn> ); } }
src/svg-icons/social/cake.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialCake = (props) => ( <SvgIcon {...props}> <path d="M12 6c1.11 0 2-.9 2-2 0-.38-.1-.73-.29-1.03L12 0l-1.71 2.97c-.19.3-.29.65-.29 1.03 0 1.1.9 2 2 2zm4.6 9.99l-1.07-1.07-1.08 1.07c-1.3 1.3-3.58 1.31-4.89 0l-1.07-1.07-1.09 1.07C6.75 16.64 5.88 17 4.96 17c-.73 0-1.4-.23-1.96-.61V21c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-4.61c-.56.38-1.23.61-1.96.61-.92 0-1.79-.36-2.44-1.01zM18 9h-5V7h-2v2H6c-1.66 0-3 1.34-3 3v1.54c0 1.08.88 1.96 1.96 1.96.52 0 1.02-.2 1.38-.57l2.14-2.13 2.13 2.13c.74.74 2.03.74 2.77 0l2.14-2.13 2.13 2.13c.37.37.86.57 1.38.57 1.08 0 1.96-.88 1.96-1.96V12C21 10.34 19.66 9 18 9z"/> </SvgIcon> ); SocialCake = pure(SocialCake); SocialCake.displayName = 'SocialCake'; SocialCake.muiName = 'SvgIcon'; export default SocialCake;
src/components/Widgets/DateControl.js
dopry/netlify-cms
import PropTypes from 'prop-types'; import React from 'react'; import DateTime from 'react-datetime'; export default class DateControl extends React.Component { componentDidMount() { if (!this.props.value) { this.props.onChange(new Date()); } } handleChange = (datetime) => { this.props.onChange(datetime); }; render() { return (<DateTime timeFormat={false} value={this.props.value} onChange={this.handleChange} />); } } DateControl.propTypes = { onChange: PropTypes.func.isRequired, value: PropTypes.object, // eslint-disable-line };
examples/todomvc/containers/Root.js
yang-wei/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
src/containers/search_bar.js
johnliu8365/Learn_Redux_Weather-Forecast-App
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }); } onFormSubmit(event) { event.preventDefault(); this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Get a five-day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary" >Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
app/javascript/mastodon/features/compose/components/upload_button.js
Craftodon/Craftodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; const messages = defineMessages({ upload: { id: 'upload_button.label', defaultMessage: 'Add media' }, }); const makeMapStateToProps = () => { const mapStateToProps = state => ({ acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']), }); return mapStateToProps; }; const iconStyle = { height: null, lineHeight: '27px', }; @connect(makeMapStateToProps) @injectIntl export default class UploadButton extends ImmutablePureComponent { static propTypes = { disabled: PropTypes.bool, onSelectFile: PropTypes.func.isRequired, style: PropTypes.object, resetFileKey: PropTypes.number, acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { if (e.target.files.length > 0) { this.props.onSelectFile(e.target.files); } } handleClick = () => { this.fileElement.click(); } setRef = (c) => { this.fileElement = c; } render () { const { intl, resetFileKey, disabled, acceptContentTypes } = this.props; return ( <div className='compose-form__upload-button'> <IconButton icon='camera' title={intl.formatMessage(messages.upload)} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} /> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.upload)}</span> <input key={resetFileKey} ref={this.setRef} type='file' multiple={false} accept={acceptContentTypes.toArray().join(',')} onChange={this.handleChange} disabled={disabled} style={{ display: 'none' }} /> </label> </div> ); } }
src/svg-icons/image/leak-add.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLeakAdd = (props) => ( <SvgIcon {...props}> <path d="M6 3H3v3c1.66 0 3-1.34 3-3zm8 0h-2c0 4.97-4.03 9-9 9v2c6.08 0 11-4.93 11-11zm-4 0H8c0 2.76-2.24 5-5 5v2c3.87 0 7-3.13 7-7zm0 18h2c0-4.97 4.03-9 9-9v-2c-6.07 0-11 4.93-11 11zm8 0h3v-3c-1.66 0-3 1.34-3 3zm-4 0h2c0-2.76 2.24-5 5-5v-2c-3.87 0-7 3.13-7 7z"/> </SvgIcon> ); ImageLeakAdd = pure(ImageLeakAdd); ImageLeakAdd.displayName = 'ImageLeakAdd'; export default ImageLeakAdd;
src/svg-icons/image/filter-1.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter1 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 10h2V5h-4v2h2v8zm7-14H7c-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 16H7V3h14v14z"/> </SvgIcon> ); ImageFilter1 = pure(ImageFilter1); ImageFilter1.displayName = 'ImageFilter1'; ImageFilter1.muiName = 'SvgIcon'; export default ImageFilter1;
src/main/resources/js/views/WelcomeView.js
fnerdrum/hendelse-datomic
import React from 'react'; import { Link } from 'react-router'; class WelcomeView extends React.Component { constructor(props) { super(props); } render() { return ( <div className="welcome-view"> <p>For enkel visning og søk i hendelser i Henvendelse.</p> </div> ); } } export default WelcomeView;
docs/src/app/components/pages/components/CircularProgress/Page.js
mtsandeep/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import circleProgressReadmeText from './README'; import circleProgressCode from '!raw!material-ui/CircularProgress/CircularProgress'; import CircleProgressExampleSimple from './ExampleSimple'; import circleProgressExampleSimpleCode from '!raw!./ExampleSimple'; import CircleProgressExampleDeterminate from './ExampleDeterminate'; import circleProgressExampleDeterminateCode from '!raw!./ExampleDeterminate'; const descriptions = { indeterminate: 'By default, the indicator animates continuously.', determinate: 'In determinate mode, the indicator adjusts to show the percentage complete, ' + 'as a ratio of `value`: `max-min`.', }; const CircleProgressPage = () => ( <div> <Title render={(previousTitle) => `Circular Progress - ${previousTitle}`} /> <MarkdownElement text={circleProgressReadmeText} /> <CodeExample title="Indeterminate progress" description={descriptions.indeterminate} code={circleProgressExampleSimpleCode} > <CircleProgressExampleSimple /> </CodeExample> <CodeExample title="Determinate progress" description={descriptions.determinate} code={circleProgressExampleDeterminateCode} > <CircleProgressExampleDeterminate /> </CodeExample> <PropTypeDescription code={circleProgressCode} /> </div> ); export default CircleProgressPage;
demo-app/src/components/ProductRow.js
nol13/fuzzball.js
import React from 'react'; import PropTypes from 'prop-types'; import styles from '../styles/productRow.module.scss'; const ProductRow = ({ data }) => <div> <p className={styles.prodrow}>{data[0].name}, Score: {data[1]} </p> </div>; ProductRow.propTypes = { data: PropTypes.array }; export default ProductRow;
src/__tests__/FuncGraph-test.js
kevinfrei/rollercoaster
import React from 'react'; import ReactDOM from 'react-dom'; import {UnboundFunctionGraph} from '../FuncGraph'; import {DemandUserFunc} from '../UserFunction'; it('renders without crashing', () => { const div = document.createElement('div'); const funcs = [ DemandUserFunc('x', 0, 1) ]; try { ReactDOM.render( <UnboundFunctionGraph funcs={funcs} selected={0} showVector={false} showCart={false} showLabels={true} scale={20} time={0} size={{width:-1,height:-1}}/>, div); } catch (e){ if (e !== 'testOnly') throw e; } });
src/components/Widget.js
dfilipidisz/overwolf-hots-talents
import React from 'react'; import cn from 'classnames'; import AppPopup from './AppPopup'; import { Motion, spring } from 'react-motion'; class MinimizedWidget extends React.Component { render () { const { closeWidget, openMain, openDetails, isDetailsOpen, openOn, placement } = this.props; const toggleProps = {}; if (openOn === 'hover') { toggleProps.onMouseEnter = openDetails; } else { toggleProps.onClick = openDetails; } const isRight = placement === 'right'; const mainClass = cn('mini-widget', { 'is-right': isRight }); const arrowClass = cn('fa', { 'fa-chevron-right': !isRight, 'fa-chevron-left': isRight, }); return ( <div className={mainClass} style={{ display: isDetailsOpen ? 'none' : 'block'}}> <AppPopup position={isRight ? 'left center' : 'right center'} title='Open Main Window' > <div className='main-toggle' onClick={openMain}><i className='fa fa-circle-o' /></div> </AppPopup> <AppPopup position={isRight ? 'left center' : 'right center'} title='Show Build' > <div className='open-details' {...toggleProps}><i className={arrowClass} /></div> </AppPopup> <AppPopup position={isRight ? 'left center' : 'right center'} title='Close In-Game Widget' > <div className='close-widget' onClick={closeWidget}><i className='fa fa-remove' /></div> </AppPopup> </div> ); } }; const levels = ['1', '4', '7', '10', '13', '16', '20']; class WidgetDetails extends React.Component { constructor() { super(); this.callClose = this.callClose.bind(this); this.state = { timeOpened: 0, } } componentWillReceiveProps(nextProps) { if (!this.props.open && nextProps.open) { this.setState({ timeOpened: Date.now() }); } } callClose() { // Add a slight no-op window to prevent flip-flopping of opening if (Date.now() - this.state.timeOpened > 200) { this.props.closeDetails(); } } render () { const { open, build, opacity, closeOn, placement } = this.props; const toggleProps = {}; if (closeOn === 'hover') { toggleProps.onMouseLeave = this.callClose; } else { toggleProps.onClick = this.callClose; } const isRight = placement === 'right'; const mainClass = cn('widget-details', { 'is-right': isRight }); const slideValue = isRight ? 230 : -230; return ( <Motion style={ { x: spring(open ? 0 : slideValue) } }> {({ x }) => ( <div className={mainClass} {...toggleProps} style={{transform: `translateX(${x}px)`, opacity, cursor: closeOn === 'click' ? 'pointer' : 'default'}}> <div className='widget-talents'> {build && build.talents.map((level, i) => { return ( <div className='talent-row' key={level.id}> <div className='lvl'><span>{levels[i]}</span></div> <div className='talent-holder clearfix'> <div className='img-holder'> <div className={`talent-pic ${build.hero.value} ${level.id}`} /> </div> <div className='text-holder'> <p>{level.title}</p> </div> </div> </div> ); })} </div> </div> )} </Motion> ); } }; class Widget extends React.Component { constructor() { super(); this.closeWidget = this.closeWidget.bind(this); this.receiveMessage = this.receiveMessage.bind(this); this.openMain = this.openMain.bind(this); this.openDetails = this.openDetails.bind(this); this.closeDetails = this.closeDetails.bind(this); this.state = { isVisible: false, ownId: null, mainId: null, isDetailsOpen: false, build: null, opacity: 1, openOn: 'hover', closeOn: 'hover', placement: 'left', position: 0.06, }; } componentDidMount() { overwolf.windows.getCurrentWindow((result) => { if (result.status === "success") { // Ensure the correct window size this.setState({ ownId: result.window.id }); overwolf.windows.changeSize(result.window.id, 240, 300); overwolf.windows.changePosition(result.window.id, 0, 50); overwolf.windows.onMessageReceived.addListener(this.receiveMessage); } else { // TODO: handle error case console.error(result); } }); } componentWillUnmount() { overwolf.windows.onMessageReceived.removeListener(this.receiveMessage); } receiveMessage(payload) { switch (payload.id) { case 'init-data': this.setState({ mainId: payload.content.mainWindowId, opacity: payload.content.settings.opacity, openOn: payload.content.settings.openOn, closeOn: payload.content.settings.closeOn, placement: payload.content.settings.placement, position: payload.content.settings.position, }); overwolf.windows.changePosition(this.state.ownId, payload.content.settings.placement === 'left' ? 0 : Math.round(window.screen.width - 240), Math.round((window.screen.height - 300) * payload.content.settings.position) ); break; case 'show-yourself': this.setState({ isVisible: true }); break; case 'hide-yourself': this.setState({ isVisible: false }); break; case 'open-build': this.setState({ build: payload.content }); break; case 'update-settings': this.setState({ opacity: payload.content.opacity, openOn: payload.content.openOn, closeOn: payload.content.closeOn, placement: payload.content.placement, position: payload.content.position, }); overwolf.windows.changePosition(this.state.ownId, payload.content.placement === 'left' ? 0 : Math.round(window.screen.width - 240), Math.round((window.screen.height - 300) * payload.content.position) ); break; } } closeWidget() { overwolf.windows.sendMessage(this.state.mainId, 'request-hide', null, () => {}); } openMain() { overwolf.windows.sendMessage(this.state.mainId, 'open-main', null, () => {}); } openDetails() { this.setState({ isDetailsOpen: true }); } closeDetails() { this.setState({ isDetailsOpen: false }); } render () { const { isVisible, isDetailsOpen, build, opacity, openOn, closeOn, placement } = this.state; if (!isVisible) { return null; } return ( <div style={{backgroundColor: 'transparent', width: '240px', height: '300px', position: 'relative'}}> <MinimizedWidget closeWidget={this.closeWidget} openMain={this.openMain} openDetails={this.openDetails} isDetailsOpen={isDetailsOpen} openOn={openOn} placement={placement} /> <WidgetDetails open={isDetailsOpen} closeDetails={this.closeDetails} build={build} opacity={opacity} closeOn={closeOn} placement={placement} /> </div> ); } } export default Widget;
src/skeletons/firstIter/layout/PageHeading.js
WapGeaR/react-redux-boilerplate-auth
import React from 'react' import Helmet from 'react-helmet' export default class PageHeading extends React.Component { render() { return ( <div className="page-heading"> <h1>{this.props.title ? this.props.title : 'Упячка попяке'}</h1> {this.props.title && <Helmet title={this.props.title} />} </div>) } }
src/components/conversation-admin/participant-header.js
pol-is/polisClientAdmin
/* * Copyright 2012-present, Polis Technology 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 for non-commercial use can be found in the PATENTS file * in the same directory. */ import React from 'react'; import Radium from 'radium'; // import _ from 'lodash'; import Flex from '../framework/flex'; // import { connect } from 'react-redux'; // import { FOO } from '../actions'; import Awesome from "react-fontawesome"; import VerifiedTwitterIcon from "../framework/verified-twitter-icon"; // const style = { // }; // @connect(state => { // return state.FOO; // }) @Radium class ParticipantHeader extends React.Component { constructor(props) { super(props); this.state = { }; } static propTypes = { /* react */ // dispatch: React.PropTypes.func, params: React.PropTypes.object, routes: React.PropTypes.array, /* component api */ style: React.PropTypes.object, fb_name: React.PropTypes.string, // foo: React.PropTypes.string } static defaultProps = { // foo: "bar" } getStyles() { return { image: { borderRadius: 3, }, name: { marginLeft: 10, marginBottom: 3, fontWeight: 700, }, }; } getRealName() { let name = ""; if (this.props.name) { name = this.props.name; } if (this.props.fb_name) { name = this.props.fb_name; } return name; } getImage() { let image = ""; if (this.props.fb_user_id) { image = ( <img src={this.props.fb_picture} style={this.getStyles().image}/> ) } else if (this.props.profile_image_url_https) { image = ( <img src={this.props.profile_image_url_https} style={this.getStyles().image}/> ) } else if (this.props.twitter_profile_image_url_https) { image = ( <img src={this.props.twitter_profile_image_url_https} style={this.getStyles().image}/> ) } return image; } facebookIcon() { return ( <a target="_blank" href={this.props.fb_link}> <Awesome style={{ fontSize: 24, color: "#3b5998", }} name={"facebook-square"} /> </a> ) } twitterIcon() { return ( <a target="_blank" href={`https://twitter.com/${this.props.screen_name}`}> <Awesome style={{ fontSize: 24, color: "#4099FF", marginLeft: 10, }} name={"twitter-square"} /> </a> ) } followers() { return ( <a target="_blank" href={`https://twitter.com/${this.props.screen_name}`} style={{ textDecoration: "none", fontWeight: 300, color: "black", marginLeft: 10 }}> <Awesome style={{ fontSize: 16, color: "#4099FF", }} name={"twitter"} /> <span style={{marginLeft: 5}}> {this.props.followers_count} </span> </a> ) } render() { const styles = this.getStyles(); return ( <Flex styleOverrides={{width: "100%"}} justifyContent="space-between" alignItems="flex-start"> <Flex alignItems="flex-start"> {this.getImage()} <Flex direction="column" alignItems="flex-start"> <span style={styles.name}> {this.getRealName()} </span> <span> {this.props.followers_count ? this.followers() : ""} </span> </Flex> {this.props.is_verified ? <VerifiedTwitterIcon/> : ""} </Flex> <div> {/*this.props.twitter_user_id ? this.props.followerCount : ""*/} {this.props.fb_user_id ? this.facebookIcon() : ""} {this.props.twitter_user_id ? this.twitterIcon() : ""} </div> </Flex> ); } } export default ParticipantHeader; /* propTypes: { // You can declare that a prop is a specific JS primitive. By default, these // are all optional. optionalArray: React.PropTypes.array, optionalBool: React.PropTypes.bool, optionalFunc: React.PropTypes.func, optionalNumber: React.PropTypes.number, optionalObject: React.PropTypes.object, optionalString: React.PropTypes.string, // Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: React.PropTypes.node, // A React element. optionalElement: React.PropTypes.element, // You can also declare that a prop is an instance of a class. This uses // JS's instanceof operator. optionalMessage: React.PropTypes.instanceOf(Message), // You can ensure that your prop is limited to specific values by treating // it as an enum. optionalEnum: React.PropTypes.oneOf(['News', 'Photos']), // An object that could be one of many types optionalUnion: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.instanceOf(Message) ]), // An array of a certain type optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), // An object with property values of a certain type optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), // An object taking on a particular shape optionalObjectWithShape: React.PropTypes.shape({ color: React.PropTypes.string, fontSize: React.PropTypes.number }), // You can chain any of the above with `isRequired` to make sure a warning // is shown if the prop isn't provided. requiredFunc: React.PropTypes.func.isRequired, // A value of any data type requiredAny: React.PropTypes.any.isRequired, */
app/containers/Franchise/index.js
prudhvisays/newsb
import React from 'react'; import { connect } from 'react-redux'; import FranchiseMap from '../../components/FranchiseForm/Map'; import FranchiseForm from '../../components/FranchiseForm'; import * as actions from './actions'; class Franchise extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <section style={{ background: '#eee', color: '#fff' }}> <div className="ink-grid" style={{ padding: 0, margin: '0 0 0 3.5em' }}> <div className="column-group quarter-horizontal-gutters"> <div className="all-50"> <FranchiseForm postFrancCord={this.props.postFrancCord} stateFranchiseGeoFence= {this.props.franchiseGeoFence} StateReqGeoFence={this.props.reqGeoFence} newFormState={this.props.newFormState} onFormChange={this.props.onFormChange} submitFranchiseData={this.props.submitFranchiseData} statefranchiseCord={this.props.franchiseCord} /> </div> <div className="all-50"> <FranchiseMap statefranchiseCord={this.props.franchiseCord} postGeoFence={this.props.postGeoFence} /> </div> </div> </div> </section> ); } } function mapStateToProps(state) { const { franchiseCord, franchiseGeoFence, reqGeoFence, newFormState } = state.get('franchise'); return { franchiseCord, franchiseGeoFence, reqGeoFence, newFormState, }; } function mapDispatchToProps(dispatch) { return { postFrancCord: (data) => { dispatch(actions.postFrancCord(data)); }, postGeoFence: (data) => { dispatch(actions.postGeoFence(data)); }, onFormChange: (data) => { dispatch(actions.onFormChange(data)); }, getPilots: (data) => { dispatch(actions.getPilots(data)); }, submitFranchiseData: (data) => { dispatch(actions.submitFranchiseData(data)); }, }; } export default connect(mapStateToProps, mapDispatchToProps)(Franchise);
modules/dreamview/frontend/src/components/StatusBar/AutoMeter.js
ycool/apollo
import React from 'react'; import { observer } from 'mobx-react'; import Speedometer from 'components/StatusBar/Speedometer'; class Meter extends React.Component { render() { const { label, percentage, meterColor, background, } = this.props; const percentageString = `${percentage}%`; return ( <div className="meter-container"> <div className="meter-label"> {label} <span className="meter-value">{percentageString}</span> </div> <span className="meter-head" style={{ borderColor: meterColor }} /> <div className="meter-background" style={{ backgroundColor: background }} > <span style={{ backgroundColor: meterColor, width: percentageString, }} /> </div> </div> ); } } @observer export default class AutoMeter extends React.Component { constructor(props) { super(props); this.setting = { brake: { label: 'Brake', meterColor: '#B43131', background: '#382626', }, accelerator: { label: 'Accelerator', meterColor: '#006AFF', background: '#2D3B50', }, }; } render() { const { throttlePercent, brakePercent, speed } = this.props; return ( <div className="auto-meter"> <Speedometer meterPerSecond={speed} /> <div className="brake-panel"> <Meter label={this.setting.brake.label} percentage={brakePercent} meterColor={this.setting.brake.meterColor} background={this.setting.brake.background} /> </div> <div className="throttle-panel"> <Meter label={this.setting.accelerator.label} percentage={throttlePercent} meterColor={this.setting.accelerator.meterColor} background={this.setting.accelerator.background} /> </div> </div> ); } }
src/components/SmartComponent.js
tiberiuc/react-redux-minimal-starter
import React from 'react' import {connect} from 'react-redux' import {pushState } from 'redux-router' class SmartComponent extends React.Component { render() { const {dispatch, pushState} = this.props; const handleRedirect = () => { console.log(this.props.location) dispatch(pushState(null, '/redirected')) } const {simpleStore, immutableStore, dispatch} = this.props return ( <div> <h1>Home page component</h1> <button onClick={handleRedirect}>Redirect</button> </div> ) } } function mapStateToProps(state){ return { simpleStore: state.simple, immutableStore: state.immutable, location: state.router.location } } export default connect(mapStateToProps, {pushState})(SmartComponent)
src/svg-icons/image/switch-camera.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageSwitchCamera = (props) => ( <SvgIcon {...props}> <path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 11.5V13H9v2.5L5.5 12 9 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); ImageSwitchCamera = pure(ImageSwitchCamera); ImageSwitchCamera.displayName = 'ImageSwitchCamera'; ImageSwitchCamera.muiName = 'SvgIcon'; export default ImageSwitchCamera;
react-dev/pages/footer.js
DeryLiu/DeryLiu.github.io
import React from 'react'; import Paper from 'material-ui/Paper'; import { blueGrey800, grey50, teal900, green900, green500, teal500, cyan500 } from 'material-ui/styles/colors'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { SignupForm } from '../components/signup_form'; import { SocialMediaStatic } from './social_media_static'; const muiTheme = getMuiTheme(darkBaseTheme, { palette: { primary1Color: blueGrey800, primary2Color: green900, primary3Color: teal900, accent1Color: green500, accent2Color: teal500, accent3Color: cyan500, textColor: grey50, alternateTextColor: grey50, //color on header //pickerHeaderColor: grey900 }, appBar: { height: 100 }, }); injectTapEventPlugin(); export const Footer = () => { return ( <MuiThemeProvider muiTheme={muiTheme}> <Paper zDepth={3} className="paper-footer-wrapper"> <footer className="site-footer"> <div className="wrapper"> <div className="footer-col-wrapper"> <div className="footer-col footer-col-1"> <ul className="contact-list"> <li>{'{{ site.react.title }}'}</li> <li><a href={'mailto:{{site.react.email}}'}>{'{{site.react.email}}'}</a></li> </ul> </div> <div className="footer-col footer-col-2" > <SocialMediaStatic /> </div> <div className="footer-col footer-col-3"> <SignupForm /> </div> </div> </div> </footer> </Paper> </MuiThemeProvider> ); };
src/client/story_box.js
jingweno/hacker-menu
import React from 'react' import _ from 'lodash' import Client from 'electron-rpc/client' import StoryList from './story_list.js' import Spinner from './spinner.js' import Menu from './menu.js' import StoryType from '../model/story_type' export default class StoryBox extends React.Component { constructor (props) { super(props) this.client = new Client() this.state = { stories: [], selected: StoryType.TOP_TYPE, status: '', version: '', upgradeVersion: '' } } componentDidMount () { var self = this self.client.request('current-version', function (err, version) { if (err) { console.error(err) return } self.setState({ version: version }) }) self.onNavbarClick(self.state.selected) } onQuitClick () { this.client.request('terminate') } onUrlClick (url) { this.client.request('open-url', { url: url }) } onMarkAsRead (id) { this.client.request('mark-as-read', { id: id }, function () { var story = _.findWhere(this.state.stories, { id: id }) story.hasRead = true this.setState({ stories: this.state.stories }) }.bind(this)) } onNavbarClick (selected) { var self = this self.setState({ stories: [], selected: selected }) self.client.localEventEmitter.removeAllListeners() self.client.on('update-available', function (err, releaseVersion) { if (err) { console.error(err) return } self.setState({ status: 'update-available', upgradeVersion: releaseVersion }) }) var storycb = function (err, storiesMap) { if (err) { return } // console.log(JSON.stringify(Object.keys(storiesMap), null, 2)) var stories = storiesMap[self.state.selected] if (!stories) { return } // console.log(JSON.stringify(stories, null, 2)) self.setState({stories: stories}) } self.client.request(selected, storycb) self.client.on(selected, storycb) } render () { var navNodes = _.map(StoryType.ALL, function (selection) { var className = 'control-item' if (this.state.selected === selection) { className = className + ' active' } return ( <a key={selection} className={className} onClick={this.onNavbarClick.bind(this, selection)}>{selection}</a> ) }, this) var content = null if (_.isEmpty(this.state.stories)) { content = <Spinner /> } else { content = <StoryList stories={this.state.stories} onUrlClick={this.onUrlClick.bind(this)} onMarkAsRead={this.onMarkAsRead.bind(this)} /> } return ( <div className='story-menu'> <header className='bar bar-nav'> <div className='segmented-control'> {navNodes} </div> </header> {content} <Menu onQuitClick={this.onQuitClick.bind(this)} status={this.state.status} version={this.state.version} upgradeVersion={this.state.upgradeVersion} /> </div> ) } }
imports/ui/components/Routes/PlaceOrderAuthenticated.js
haraneesh/mydev
import React from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect } from 'react-router-dom'; const PlaceOrderAuthenticated = ({ layout: Layout, roles, authenticated, component: Component, ...rest }) => ( <Route {...rest} render={props => ( authenticated ? (<Layout {...props} isAdmin={roles.indexOf('admin') !== -1} authenticated {...rest} > <Component {...props} authenticated {...rest} roles={roles} /> </Layout>) : (<Redirect to="/login" />) )} /> ); PlaceOrderAuthenticated.propTypes = { routeName: PropTypes.string.isRequired, roles: PropTypes.array.isRequired, authenticated: PropTypes.bool.isRequired, component: PropTypes.func.isRequired, layout: PropTypes.node.isRequired, }; export default PlaceOrderAuthenticated;
test/client/containers/thumbs.js
berkeley-homes/near-miss-positive-intervention
import test from 'tape' import React from 'react' import { shallow } from 'enzyme' import { Thumbs } from '../../../src/client/containers/thumbs.js' import ThumbsUp from '../../../src/client/components/thumbs_up.js' import ThumbsDown from '../../../src/client/components/thumbs_down.js' test('<Thumbs />', t => { const wrapper = shallow(<Thumbs />) t.equal(wrapper.find(ThumbsDown).length, 1, 'has thumbs down') t.equal(wrapper.find(ThumbsUp).length, 1, 'has thumbs up') t.end() })
client/analytics/components/partials/filter/popUps/FilterItemXAxelList.js
Haaarp/geo
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import ToggleButtonList from 'konux/common/components/ToggleButtonList'; import {analytics} from './../../../../actions'; import { ChartType, AxelType } from './../../../../constants'; class XAxelList extends React.Component { getXAxelList(){ switch(this.props.selectedType){ case ChartType.SHOW_ASSET_DISTRIBUTION_CANDLE_CHART: case ChartType.SHOW_GROUP_DISTRIBUTION_CANDLE_CHART: return [ { name: AxelType.AXIS_DATE, id: 1 }, { name: AxelType.AXIS_SWITCH_ID, id: 2 } ]; case ChartType.SHOW_ASSET_CORRELATION_CHART: case ChartType.SHOW_GROUP_CORRELATION_CHART: return [ { name: AxelType.AXIS_LOAD, id: 1 }, { name: AxelType.AXIS_WSH, id: 2 } ]; case ChartType.SHOW_ASSET_DISTRIBUTION_LINE_CHART: return [ { name: AxelType.AXIS_DATE, id: 1 }, { name: AxelType.AXIS_SWITCH_ID, id: 2 } ]; case ChartType.SHOW_ASSET_PREDICTION_CHART: default: return null; } } render(){ return <ToggleButtonList selectedList={[this.props.selectedXAxel]} list={this.getXAxelList()} onApply={this.props.xAxelListClick}/>; } } const stateMap = (state, props, ownProps) => { return { selectedType: state.selected.chart.type? state.selected.chart.type.name : null, selectedXAxel: state.selected.chart.selectedXAxel ? state.selected.chart.selectedXAxel.id : 1 }; }; function mapDispatchToProps(dispatch) { return { xAxelListClick: bindActionCreators(analytics.chart.xAxelListClick, dispatch) }; }; export default connect(stateMap, mapDispatchToProps)(XAxelList);
src/client/shell/index.js
jordond/xmlr
import React from 'react' import DevTools from 'mobx-react-devtools' // Add components or styles /** * Shell component * * Top most level of all components in the application, all routes and children will be placed inside * Contains mobx dev tools for development * * @param {Object} props - See proptypes * @returns React component */ function Shell(props) { if (process.env.NODE_ENV === 'development') { return ( <div> {props.children} <DevTools /> </div> ) } return <div>{props.children}</div> } /** * @property {Object} propTypes - Require prop types for app to function */ Shell.propTypes = { children: React.PropTypes.object } /** * @exports Shell */ export default Shell
app/jsx/conferences/renderAlternatives.js
djbender/canvas-lms
/* * Copyright (C) 2020 - 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 {render} from 'react-dom' import PropTypes from 'prop-types' import {Alert} from '@instructure/ui-alerts' import {ApplyTheme} from '@instructure/ui-themeable' import I18n from 'i18n!conferences_alternatives' import {Text} from '@instructure/ui-text' import {Img} from '@instructure/ui-img' import {Flex} from '@instructure/ui-flex' import {View} from '@instructure/ui-view' import responsiviser from 'canvas-planner/lib/components/responsiviser' import {Link} from '@instructure/ui-link' import ZoomIcon from './svg/zoom.svg' import MeetIcon from './svg/meet.svg' import TeamsIcon from './svg/teams.svg' const theme = { [Alert.theme]: { boxShadow: 'none' } } const visitZoomUrl = 'https://zoom.com/meeting/schedule' const visitMeetUrl = 'https://meet.google.com/_meet' const learnMeetUrl = 'https://community.canvaslms.com/docs/DOC-18570-google-hangouts-meet' const learnTeamsUrl = 'https://community.canvaslms.com/docs/DOC-18558-microsoft-teams-meetings-in-canvas' function ConferenceProvider({imageSource, title, text, responsiveSize}) { const skinny = responsiveSize === 'medium' return ( <Flex direction={skinny ? 'row' : 'column'} alignItems="stretch"> <Flex.Item height={skinny ? null : '10rem'} width={skinny ? '10rem' : null} background="secondary" margin="0 medium 0 0" > <Flex alignItems="center" justifyItems="center" height="100%"> <Flex.Item padding="small"> <Img src={imageSource} title={title} /> </Flex.Item> </Flex> </Flex.Item> <Flex.Item shouldShrink padding="small x-small"> <Text size="large" weight="bold"> {title} </Text> <Text size="small"> {text.map((content, i) => ( // eslint-disable-next-line react/no-array-index-key <View key={i} as="div" padding="x-small 0"> {content} </View> ))} </Text> </Flex.Item> </Flex> ) } ConferenceProvider.propTypes = { imageSource: PropTypes.string.isRequired, title: PropTypes.string.isRequired, text: PropTypes.arrayOf(PropTypes.node).isRequired, responsiveSize: PropTypes.oneOf(['small', 'medium', 'large']).isRequired } const Zoom = props => ( <ConferenceProvider {...props} imageSource={ZoomIcon} title={I18n.t('Zoom')} text={[ I18n.t( 'Paste Zoom into Calendar Events, Announcements, Discussions, and anywhere you use the Rich Content Editor (RCE).' ), [ <Link href={visitZoomUrl}>{I18n.t('Visit Zoom')}</Link>, I18n.t( 'to create a link you can use in Canvas. You’ll need to sign-up for a Zoom account if you don’t already have one.' ) ] // <Link href={learnZoomUrl}>{I18n.t('Learn how to use Zoom in Canvas.')}</Link> ]} /> ) const Meet = props => ( <ConferenceProvider {...props} imageSource={MeetIcon} title={I18n.t('Google Meet')} text={[ I18n.t( 'Paste Google Meet links into Calendar Events, Announcements, Discussions, and anywhere you use the Rich Content Editor (RCE)' ), [ <Link href={visitMeetUrl}>{I18n.t('Visit Google Meet')}</Link>, I18n.t( 'to create a link you can use in Canvas. You’ll need a Google account to use Google Meet.' ) ], <Link href={learnMeetUrl}>{I18n.t('Learn how to use Google Meet in Canvas')}</Link> ]} /> ) const Teams = props => ( <ConferenceProvider {...props} imageSource={TeamsIcon} title={I18n.t('Microsoft Teams')} text={[ I18n.t( 'If your school uses Microsoft Teams, you can use the Enhanced Rich Content Editor (RCE) to easily add a Team room while creating Calendar Events, Announcements, discussions posts and more.' ), <Link href={learnTeamsUrl}>{I18n.t('Learn how to use Microsoft Teams in Canvas')}</Link> ]} /> ) function ConferenceAlternatives({responsiveSize}) { return ( <ApplyTheme theme={theme}> <Alert margin="none none medium none" variant="warning"> {I18n.t(`Conferences, powered by BigBlueButton, is unable to handle current demand. Consider upgrading to Premium BigBlueButton or use one of the following video conferencing providers. Please talk to your local admin for additional guidance.`)} </Alert> <View as="div" borderWidth="small 0 0 0" borderColor="primary" padding="medium 0 0 0"> <Flex direction={responsiveSize === 'large' ? 'row' : 'column'} alignItems="start"> <Flex.Item shouldGrow size={responsiveSize === 'large' ? '0' : null}> <Zoom responsiveSize={responsiveSize} /> </Flex.Item> <Flex.Item shouldGrow size={responsiveSize === 'large' ? '0' : null} padding={responsiveSize === 'large' ? '0 large' : 'large 0'} > <Meet responsiveSize={responsiveSize} /> </Flex.Item> <Flex.Item shouldGrow size={responsiveSize === 'large' ? '0' : null}> <Teams responsiveSize={responsiveSize} /> </Flex.Item> </Flex> </View> </ApplyTheme> ) } ConferenceAlternatives.propTypes = { responsiveSize: PropTypes.oneOf(['small', 'medium', 'large']) } const ResponsiveConferenceAlternatives = responsiviser()(ConferenceAlternatives) export default function renderConferenceAlternatives() { const $container = document.getElementById('conference-alternatives-container') render(<ResponsiveConferenceAlternatives />, $container) }
src/components/ui/PremiumFeatureContainer/index.js
meetfranz/franz
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import PropTypes from 'prop-types'; import { defineMessages, intlShape } from 'react-intl'; import injectSheet from 'react-jss'; import { oneOrManyChildElements } from '../../../prop-types'; import UserStore from '../../../stores/UserStore'; import styles from './styles'; import { gaEvent } from '../../../lib/analytics'; import FeaturesStore from '../../../stores/FeaturesStore'; const messages = defineMessages({ action: { id: 'premiumFeature.button.upgradeAccount', defaultMessage: '!!!Upgrade account', }, }); @inject('stores', 'actions') @injectSheet(styles) @observer class PremiumFeatureContainer extends Component { static propTypes = { classes: PropTypes.object.isRequired, condition: PropTypes.oneOfType([ PropTypes.bool, PropTypes.func, ]), gaEventInfo: PropTypes.shape({ category: PropTypes.string.isRequired, event: PropTypes.string.isRequired, label: PropTypes.string, }), }; static defaultProps = { condition: null, gaEventInfo: null, }; static contextTypes = { intl: intlShape, }; render() { const { classes, children, actions, condition, stores, gaEventInfo, } = this.props; const { intl } = this.context; let showWrapper = !!condition; if (condition === null) { showWrapper = !stores.user.data.isPremium; } else if (typeof condition === 'function') { showWrapper = condition({ isPremium: stores.user.data.isPremium, features: stores.features.features, }); } return showWrapper ? ( <div className={classes.container}> <div className={classes.titleContainer}> <p className={classes.title}>Premium Feature</p> <button className={classes.actionButton} type="button" onClick={() => { actions.ui.openSettings({ path: 'user' }); if (gaEventInfo) { const { category, event, label } = gaEventInfo; gaEvent(category, event, label); } }} > {intl.formatMessage(messages.action)} </button> </div> <div className={classes.content}> {children} </div> </div> ) : children; } } PremiumFeatureContainer.wrappedComponent.propTypes = { children: oneOrManyChildElements.isRequired, stores: PropTypes.shape({ user: PropTypes.instanceOf(UserStore).isRequired, features: PropTypes.instanceOf(FeaturesStore).isRequired, }).isRequired, actions: PropTypes.shape({ ui: PropTypes.shape({ openSettings: PropTypes.func.isRequired, }).isRequired, }).isRequired, }; export default PremiumFeatureContainer;
mobile/mock ups/albums/src/components/AlbumList.js
parammehta/TravLendar
import React, { Component } from 'react'; import { ScrollView } from 'react-native'; import axios from 'axios'; import AlbumDetail from './AlbumDetail'; class AlbumList extends Component { state = { albums: []}; componentWillMount() { axios.get('https://rallycoding.herokuapp.com/api/music_albums') .then(response => this.setState({albums: response.data })); } renderAlbums() { // return this.state.albums.map(album => <Text key={ album.title } >{ album.title } </Text>); return this.state.albums.map(album => <AlbumDetail key={album.title} album={album}/>); } render() { console.log(this.state); return ( <ScrollView> { this.renderAlbums()} </ScrollView> ); } } export default AlbumList;
Libraries/Components/WebView/WebView.ios.js
browniefed/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var ReactNative = require('react/lib/ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var PropTypes = React.PropTypes; var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any, code: any, description: any, } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ class WebView extends React.Component { static JSNavigationScheme = JSNavigationScheme; static NavigationType = NavigationType; static propTypes = { ...View.propTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: View.propTypes.style, /** * Determines the types of data converted to clickable URLs in the web view’s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `true`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, }; state = { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; componentWillMount() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } } render() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); } /** * Go forward one page in the web view's history. */ goForward = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }; /** * Go back one page in the web view's history. */ goBack = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }; /** * Reloads the current page. */ reload = () => { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }; /** * Stop loading the current page. */ stopLoading = () => { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }; /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState = (event: Event) => { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }; /** * Returns the native `WebView` node. */ getWebViewHandle = (): any => { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }; _onLoadingStart = (event: Event) => { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }; _onLoadingError = (event: Event) => { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }; _onLoadingFinish = (event: Event) => { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }; } var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
test/__fixtures__/Standard.js
gilbarbara/react-joyride
import React from 'react'; import PropTypes from 'prop-types'; import Joyride, { STATUS } from '../../src/index'; import tourSteps from './steps'; const filteredSteps = tourSteps .filter((d, i) => i !== 3) .map(d => { if (d.target === '.mission button') { d.target = '.mission h2'; } return d; }); export default class Standard extends React.Component { constructor(props) { super(props); const steps = [...filteredSteps]; if (props.withCentered) { steps.push({ target: 'body', placement: 'center', content: "Let's begin our journey", textAlign: 'center', }); } this.state = { run: false, steps, }; } static propTypes = { callback: PropTypes.func.isRequired, }; handleClickStart = () => { this.setState({ run: true, }); }; handleJoyrideCallback = data => { const { callback } = this.props; const { status } = data; if ([STATUS.FINISHED, STATUS.SKIPPED].includes(status)) { this.setState({ run: false }); } callback(data); }; render() { const { run, steps } = this.state; return ( <div className="demo"> <Joyride run={run} steps={steps} continuous scrollToFirstStep showSkipButton={true} callback={this.handleJoyrideCallback} /> <main> <div className="hero"> <div className="container"> <div className="hero__content"> <h1> <span>Create walkthroughs and guided tours for your ReactJS apps.</span> </h1> <button className="hero__start" onClick={this.handleClickStart} type="button"> Let's Go! </button> </div> </div> </div> <div className="demo__section projects"> <div className="container"> <h2> <span>Projects</span> </h2> <div className="list"> <div> <img src="http://placehold.it/800x600/ff0044/ffffff?txtsize=50&text=ASBESTOS" alt="ASBESTOS" /> </div> <div> <img src="http://placehold.it/800x600/00ff44/ffffff?txtsize=50&text=GROW" alt="GROW" /> </div> <div> <img src="http://placehold.it/800x600/333/ffffff?txtsize=50&text=∂Vo∑" alt="∂Vo∑" /> </div> </div> </div> </div> <div className="demo__section mission"> <div className="container"> <h2> <span>Mission</span> </h2> </div> </div> <div className="demo__section about"> <div className="container"> <h2> <span>About</span> </h2> </div> </div> </main> <footer className="demo__footer"> <div className="container"> <button type="button"> <span /> </button> JOYRIDE </div> </footer> </div> ); } }
src/index.js
wengyian/project-manager-system
/** * Created by 51212 on 2017/4/7. */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter as Router, Route, browserHistory} from 'react-router-dom'; //import { Router, Route, hashHistory } from 'react-router'; //import createBrowserHistroy from 'history/createBrowserHistory'; import LoginIn from './components/loginIn/loginIn'; import ProjectManageIndex from './components/projectManageIndex/projectManageIndex'; //const newHistroy = createBrowserHistroy(); class App extends Component{ render(){ return( <Router history={ browserHistory }> <div> <Route exact path="/" component={LoginIn}></Route> <Route path="/ProjectManageIndex" component={ProjectManageIndex}></Route> </div> </Router> ) } }; ReactDOM.render( <App></App>, document.getElementById('container') ); //ReactDOM.render( // <LoginIn></LoginIn>, // document.getElementById('container') //);
app/redux/root.js
andreipreda/coconut
import React from 'react'; import { Provider } from 'react-redux'; import store from './store'; import { AppRouter } from './router'; export const Root = () => ( <Provider store={store}> <AppRouter /> </Provider> );
src/higherOrders/Sort.js
Lobos/react-ui
import React from 'react' import PropTypes from '../utils/proptypes' import { isEmpty } from '../utils/objects' import PureRender from '../mixins/PureRender' const defaultSort = (key, asc) => (a, b) => { let x = a[key] let y = b[key] if (asc === 0) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)) } else { return ((x > y) ? -1 : ((x < y) ? 1 : 0)) } } export default function (Component) { class Sort extends React.Component { constructor (props) { super(props) this.state = {} this.handleSort = this.handleSort.bind(this) } handleSort (key, asc, fn) { this.setState({ key, asc, fn }) this.props.onSort && this.props.onSort(key, asc) } sort (data, { key, asc, fn }) { if (!Array.isArray(data)) return data return data.sort(typeof fn === 'function' ? fn : defaultSort(key, asc)) } render () { const state = this.state const { data, ...props } = this.props let sortData = isEmpty(state) ? data : this.sort(data, state) return ( <Component {...props} onSort={this.handleSort} sortStatus={{ key: state.key, asc: state.asc }} data={sortData} /> ) } } Sort.propTypes = { data: PropTypes.array_element_string, onSort: PropTypes.func } return PureRender()(Sort) }
frontend/src/components/editor/index.js
1905410/Misago
// jshint ignore:start import React from 'react'; import Code from './actions/code'; import Emphasis from './actions/emphasis'; import Hr from './actions/hr'; import Image from './actions/image'; import Link from './actions/link'; import Striketrough from './actions/striketrough'; import Strong from './actions/strong'; import Quote from './actions/quote'; import AttachmentsEditor from './attachments'; import Upload from './attachments/upload-button/'; import MarkupPreview from './markup-preview'; import * as textUtils from './textUtils'; import Button from 'misago/components/button'; import misago from 'misago'; import ajax from 'misago/services/ajax'; import modal from 'misago/services/modal'; import snackbar from 'misago/services/snackbar'; export default class extends React.Component { constructor(props) { super(props); this.state = { isPreviewLoading: false }; } onPreviewClick = () => { if (this.state.isPreviewLoading) { return; } this.setState({ isPreviewLoading: true }); ajax.post(misago.get('PARSE_MARKUP_API'), {post: this.props.value}).then((data) => { modal.show( <MarkupPreview markup={data.parsed} /> ); this.setState({ isPreviewLoading: false }); }, (rejection) => { if (rejection.status === 400) { snackbar.error(rejection.detail); } else { snackbar.apiError(rejection); } this.setState({ isPreviewLoading: false }); }); }; replaceSelection = (operation) => { operation(textUtils.getSelectionText(), this._replaceSelection); }; _replaceSelection = (newValue) => { this.props.onChange({ target: { value: textUtils.replace(newValue) } }); }; render() { return ( <div className="editor-border"> <textarea className="form-control" defaultValue={this.props.value} disabled={this.props.loading} id="editor-textarea" onChange={this.props.onChange} rows="9" ></textarea> <div className="editor-footer"> <Strong className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Emphasis className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Striketrough className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Hr className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Link className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Image className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Quote className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Code className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} replaceSelection={this.replaceSelection} /> <Upload className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} /> <Button className="btn-default btn-sm pull-left" disabled={this.props.loading || this.state.isPreviewLoading} onClick={this.onPreviewClick} type="button" > {gettext("Preview")} </Button> <Button className="btn-primary btn-sm pull-right" loading={this.props.loading} > {this.props.submitLabel || gettext("Post")} </Button> <button className="btn btn-default btn-sm pull-right" disabled={this.props.loading} onClick={this.props.onCancel} type="button" > {gettext("Cancel")} </button> <Protect canProtect={this.props.canProtect} disabled={this.props.loading} onProtect={this.props.onProtect} onUnprotect={this.props.onUnprotect} protect={this.props.protect} /> </div> <AttachmentsEditor attachments={this.props.attachments} onAttachmentsChange={this.props.onAttachmentsChange} placeholder={this.props.placeholder} replaceSelection={this.replaceSelection} /> </div> ); } } export function Protect(props) { if (props.canProtect) { return ( <button className="btn btn-icon btn-default btn-sm pull-right" disabled={props.disabled} onClick={props.protect ? props.onUnprotect : props.onProtect} title={props.protect ? gettext('Protected') : gettext('Protect')} type="button" > <span className="material-icon"> {props.protect ? 'lock' : 'lock_outline'} </span> </button> ); } else { return null; } }
server/server.js
tranphong001/BIGVN
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } app.use('/static', Express.static('./static')); app.use('/fonts', Express.static('./fonts')); app.use('/images', Express.static('./client/images')); app.use('/photo', Express.static('./public')); app.use('/banner', Express.static('../adminBig/banner')); app.use('/blog', Express.static('./blog')); // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; import helmet from 'helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import news from './routes/news.routes'; import users from './routes/user.routes'; import categories from './routes/category.routes'; import cities from './routes/city.routes'; import districts from './routes/district.routes'; import wards from './routes/ward.routes'; import banners from './routes/banner.routes'; import topics from './routes/topic.routes'; import settings from './routes/setting.routes'; import keywords from './routes/keyword.routes'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } }); app.use(helmet.xssFilter()); app.use(helmet.frameguard({ action: 'deny' })); app.use(helmet.noSniff()); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '30mb' })); app.use(bodyParser.urlencoded({ limit: '30mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist/client'))); app.use('/api', [banners, settings, topics, cities, districts, wards, categories, users, keywords, news]); // Render Initial HTML {/*<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">*/} {/*<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">*/} {/*<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">*/} {/*<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">*/} {/*<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">*/} const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link rel="stylesheet" href="/static/font-awesome.min.css"> <link rel="stylesheet" href="/static/bootstrap.min.css"> <link rel="stylesheet" href="/static/bootstrap-theme.min.css"> <link rel="stylesheet" href="/static/materialIcons/materialIcons.css"> </head> <body> <div id="root"><div>${html}</div></div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <RouterContext {...renderProps} /> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app const server = app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
client/channel/helpers/clickableItem.js
iiet/iiet-chat
import React from 'react'; import { css } from '@rocket.chat/css-in-js'; export function clickableItem(WrappedComponent) { const clickable = css` cursor: pointer; border-bottom: 2px solid #F2F3F5 !important; &:hover, &:focus { background: #F7F8FA; } `; return (props) => <WrappedComponent className={clickable} tabIndex={0} {...props}/>; }
src/index.js
ndemianc/react_app
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import Board from './components/board'; import { observe } from './components/game'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); const rootElement = document.querySelector('.container'); observe(rookPosition => ReactDOM.render( <Board rookPosition={rookPosition} /> , rootElement ) );
node_modules/semantic-ui-react/dist/es/collections/Table/TableFooter.js
jessicaappelbaum/cljs-update
import React from 'react'; import { META } from '../../lib'; import TableHeader from './TableHeader'; /** * A table can have a footer. */ function TableFooter(props) { return React.createElement(TableHeader, props); } TableFooter.handledProps = ['as']; TableFooter._meta = { name: 'TableFooter', type: META.TYPES.COLLECTION, parent: 'Table' }; TableFooter.defaultProps = { as: 'tfoot' }; export default TableFooter;
docs/src/app/components/pages/components/DropDownMenu/ExampleLabeled.js
ruifortes/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default class DropDownMenuLabeledExample extends React.Component { constructor(props) { super(props); this.state = {value: 2}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} label="5 am - 12 pm" primaryText="Morning" /> <MenuItem value={2} label="12 pm - 5 pm" primaryText="Afternoon" /> <MenuItem value={3} label="5 pm - 9 pm" primaryText="Evening" /> <MenuItem value={4} label="9 pm - 5 am" primaryText="Night" /> </DropDownMenu> ); } }
www/src/layouts/index.js
tsuyoshiwada/react-drip-form
import React from 'react'; /* eslint-disable import/no-extraneous-dependencies */ import 'prismjs'; import 'prismjs/components/prism-bash'; import 'prismjs/components/prism-javascript'; import 'prismjs/components/prism-typescript'; import 'prismjs/components/prism-jsx'; import 'prismjs/components/prism-css'; import 'prismjs/components/prism-json'; import 'prismjs/components/prism-markdown'; import 'prismjs/themes/prism.css'; /* eslint-enable import/no-extraneous-dependencies */ import 'normalize.css'; import '../css/style.css'; export default ({ children }) => ( <div> {children()} </div> );
components/common/icons.js
DarcyChan/darcychan.com
/* Icon Component. A common component to render an SVG icon. */ import React from 'react'; import ArrowRight from 'assets/arrow-right.svg'; import Close from 'assets/close.svg'; import Logo from 'assets/logo.svg'; import Menu from 'assets/menu.svg'; import Photo from 'assets/photo.svg'; export default class Icon extends React.Component { render() { const { glyph, ...props } = this.props; return ( <svg {...props}> <use xlinkHref={`#${glyph.id}`} /> </svg> ); } } export const Glyph = { ArrowRight: ArrowRight, Close: Close, Logo: Logo, Menu: Menu, Photo: Photo };
src/ColumnMarkers.js
ornl-sava/vis-react-components
import React from 'react' import PropTypes from 'prop-types' import { setEase } from './util/d3' import SVGComponent from './SVGComponent' // NOTE: Fills top margin with rect column markers // Requires a top margin greater than 5px, xScale, and the data // Expects 2D data like heatmap class ColumnMarkers extends React.Component { render () { let { className, data, onClick, xScale, xAccessor, colorScale, chartWidth, margin } = this.props let y = -margin.top let height = (margin.top - 2 > 5) ? margin.top - 2 : 5 return ( <g className={className}> {data[0].bins.map((d, i) => { // Get width of column let width = (i + 1 < data[0].bins.length) ? xScale(data[0].bins[i + 1][xAccessor.key]) : chartWidth width -= xScale(d[xAccessor.key]) // Get total value for column let total = 0 for (let j = 0; j < data.length; j++) { total += data[j].bins[i][xAccessor.key] } return ( <SVGComponent Component='rect' key={i} data={d} index={i} x={xScale(d[xAccessor.key])} y={y} fill={colorScale(total)} width={width} height={height} onClick={onClick} onUpdate={{ func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('x', props.x) .attr('y', props.y) .attr('width', props.width) .attr('height', props.height) .attr('fill', props.fill) return transition } }} /> ) })} </g> ) } } ColumnMarkers.defaultProps = { data: [], xAccessor: { key: 'key', value: 'value' }, onClick: () => {}, className: 'columnMarker', margin: { top: 0, right: 0, bottom: 0, left: 0 }, chartWidth: 0 } ColumnMarkers.propTypes = { data: PropTypes.array, colorScale: PropTypes.any, xScale: PropTypes.any, xAccessor: PropTypes.any, onClick: PropTypes.func, className: PropTypes.string, margin: PropTypes.object, chartWidth: PropTypes.number } export default ColumnMarkers
client/__tests__/components/Admin/AdminBooks.spec.js
amarachukwu-agbo/hello-books
import React from 'react'; import sinon from 'sinon'; import { shallow } from 'enzyme'; import AdminBooks from '../../../components/Admin/AdminBooks.jsx'; const props = { books: [ { id: 1, title: 'Half of a yellow sun', quantity: 20, description: 'An enchanting novel', subject: 'Fiction', author: 'Ngozi Adichie', imageURL: 'https://www.images.png', }, { id: 2, title: 'Her every wish', quantity: 10, description: 'An enchanting novel', subject: 'Fiction', author: 'Ngozi Adichie', imageURL: 'https://www.images.png', }, ], deleteBook: sinon.spy(() => Promise.resolve()), setBookForEdit: sinon.spy(() => Promise.resolve()), }; describe('<AdminBooks>', () => { it('should display a table with the available books', () => { const wrapper = shallow(<AdminBooks { ...props }/>); expect(wrapper).toMatchSnapshot(); }); it('should not display table if there are no available books', () => { const wrapper = shallow(<AdminBooks books = {[]} />); expect(wrapper.find('p').text()).toEqual('You have not added any books'); expect(wrapper.find('table').exists()).toBeFalsy(); expect(wrapper.find('div').length).toBe(1); }); it('should call fuction setBookForEdit() when edit button is clicked', () => { const wrapper = shallow(<AdminBooks { ...props }/>); wrapper.find('#editButton0').simulate('click'); expect(props.setBookForEdit.calledOnce).toEqual(true); expect(props.setBookForEdit.calledWith(1, 0)); }); it('should calls fuction deleteBook when delete button is clicked', () => { const wrapper = shallow(<AdminBooks { ...props }/>); wrapper.find('#deleteButton0').simulate('click'); expect(props.deleteBook.calledOnce).toEqual(true); expect(props.deleteBook.calledWith(1)).toEqual(true); }); });
client/src/javascript/components/sidebar/DiskUsage.js
jfurrow/flood
import {FormattedMessage} from 'react-intl'; import React from 'react'; import EventTypes from '../../constants/EventTypes'; import DiskUsageStore from '../../stores/DiskUsageStore'; import Size from '../general/Size'; import Tooltip from '../general/Tooltip'; import connectStores from '../../util/connectStores'; import ProgressBar from '../general/ProgressBar'; import SettingsStore from '../../stores/SettingsStore'; const DiskUsageTooltipItem = ({label, value}) => { return ( <li className="diskusage__details-list__item"> <label className="diskusage__details-list__label">{label}</label> <Size className="diskuage__size-used" value={value} /> </li> ); }; class DiskUsage extends React.Component { getDisks() { const {disks, mountPoints} = this.props; const diskMap = disks.reduce((disksByTarget, disk) => { disksByTarget[disk.target] = disk; return disksByTarget; }, {}); return mountPoints .filter(target => target in diskMap) .map(target => diskMap[target]) .map(d => { return ( <li key={d.target} className="sidebar-filter__item sidebar__diskusage"> <Tooltip content={ <ul className="diskusage__details-list"> <DiskUsageTooltipItem value={d.used} label={<FormattedMessage id="status.diskusage.used" defaultMessage="Used" />} /> <DiskUsageTooltipItem value={d.avail} label={<FormattedMessage id="status.diskusage.free" defaultMessage="Free" />} /> <DiskUsageTooltipItem value={d.size} label={<FormattedMessage id="status.diskusage.total" defaultMessage="Total" />} /> </ul> } position="top" wrapperClassName="diskusage__item"> <div className="diskusage__text-row"> {d.target} <span>{Math.round((100 * d.used) / d.size)}%</span> </div> <ProgressBar percent={(100 * d.used) / d.size} /> </Tooltip> </li> ); }); } render() { const disks = this.getDisks(); if (disks.length === 0) { return null; } return ( <ul className="sidebar-filter sidebar__item"> <li className="sidebar-filter__item sidebar-filter__item--heading"> <FormattedMessage id="status.diskusage.title" defaultMessage="Disk Usage" /> </li> {disks} </ul> ); } } export default connectStores(DiskUsage, () => [ { store: DiskUsageStore, event: EventTypes.DISK_USAGE_CHANGE, getValue: ({store}) => ({ disks: store.getDiskUsage(), }), }, { store: SettingsStore, event: EventTypes.SETTINGS_CHANGE, getValue: ({store}) => { return { mountPoints: store.getFloodSettings('mountPoints'), }; }, }, ]);
src/index.js
kfergin/dragging-boxes-example
import React, { Component } from 'react'; import { render } from 'react-dom'; import { TransitionMotion, spring } from 'react-motion'; import uuid from 'uuid'; import classNames from 'classnames'; import './styles/main.scss'; class Box extends Component { constructor(props) { super(props); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); } handleMouseDown(e) { this.props.handleMouseDown(e, this.props.id); } handleTouchStart(e) { e.preventDefault(); this.props.handleTouchStart(e, this.props.id); } render() { const {opacity, left, top, id} = this.props; return ( <div className="box" style={{ opacity: opacity, left: `${left}px`, top: `${top}px` }} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart} /> ); } } class Container extends Component { constructor(props) { super(props); // Determine if we're responding to touch or click events this.touchDebounce = undefined; this.handleGlobalTouch = this.handleGlobalTouch.bind(this); this.handleGlobalMouseover = this.handleGlobalMouseover.bind(this); // Notify when Shift is pressed. CSS purposes. this.handleKeyUpDown = this.handleKeyUpDown.bind(this); // Adding, moving, and removing boxes this.addBox = this.addBox.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); this.selectBox = this.selectBox.bind(this); this.removeBox = this.removeBox.bind(this); this.handleMove = this.handleMove.bind(this); this.handleRelease = this.handleRelease.bind(this); // Initial state const id = uuid(), left = 0, top = 0; this.state = { touchBased: 'ontouchstart' in window, boxes: { byID: {[id]: {id, left, top}}, allIDs: [id] }, selectedBox: null, lastSelect: 0, removing: false }; } // would want to remove these listeners if component were part of larger app componentDidMount() { document.addEventListener('touchstart', this.handleGlobalTouch); document.addEventListener('mouseover', this.handleGlobalMouseover); document.querySelector('html').addEventListener('keydown', this.handleKeyUpDown); document.querySelector('html').addEventListener('keyup', this.handleKeyUpDown); } handleGlobalTouch() { clearTimeout(this.touchDebounce); if (!this.state.touchBased) this.setState({touchBased: true}); this.touchDebounce = setTimeout(() => { this.touchDebounce = undefined; }, 500) } handleGlobalMouseover() { if (this.touchDebounce === undefined && this.state.touchBased) this.setState({touchBased: false}); } handleKeyUpDown(e) { if (e.which === 16) { this.setState(prevState => ({ ...prevState, removing: !prevState.removing })); } } addBox(e) { if (this.state.selectedBox) return; const id = uuid(), left = 0, top = 0; this.setState(prevState => ({ ...prevState, boxes: { byID: { ...prevState.boxes.byID, [id]: {id, left, top} }, allIDs: [...prevState.boxes.allIDs, id] } })); } selectBox(e, id, now) { let {clientX, clientY} = e; if (e.type === 'touchstart') { ({clientX, clientY} = e.changedTouches[0]); } this.setState(prevState => { // Possible to "select" a box as it's transition out. // Potential problem bc it's out of state but kept in TransitionMotion const box = prevState.boxes.byID[id], selectedBox = !box ? null : { id, diffX: clientX - box.left, diffY: clientY - box.top }; return { ...prevState, lastSelect: now, selectedBox }; }); } removeBox(id) { this.setState(prevState => { const {[id]: toRemove, ...rest} = prevState.boxes.byID; return { ...prevState, selectedBox: null, boxes: { byID: rest, allIDs: prevState.boxes.allIDs.filter(aid => aid !== id) } }; }); } handleMouseDown(e, id) { if (this.state.touchBased) return; const now = Date.now(); if (e.shiftKey) { this.removeBox(id); } else { this.selectBox(e, id, now); } } handleTouchStart(e, id) { const now = Date.now(); if (now - this.state.lastSelect > 250) { this.selectBox(e, id, now); } else { this.removeBox(id); } } handleMove(e) { if (!this.state.selectedBox) return; let {clientX, clientY} = e; if (e.type === 'touchmove') { e.preventDefault(); ({clientX, clientY} = e.changedTouches[0]); } this.setState(prevState => { const {id, diffX, diffY} = prevState.selectedBox; return { ...prevState, boxes: { ...prevState.boxes, byID: { ...prevState.boxes.byID, [id]: { id, left: clientX - diffX, top: clientY - diffY } } } }; }); } handleRelease(e) { this.setState(prevState => ({ ...prevState, selectedBox: null })); } render() { const containerClasses = classNames({ "container": true, "grabbing": this.state.selectedBox, "removing": this.state.removing }); return ( <div className={containerClasses} onMouseMove={this.handleMove} onTouchMove={this.handleMove} onMouseUp={this.handleRelease} onTouchEnd={this.handleRelease} > <div className="instructions"> <h4>Drag some boxes!</h4> <ul> <li>Add boxes by {this.state.touchBased ? 'tapping' : 'hovering over'} the top-left area of the screen</li> <li>To remove, {this.state.touchBased ? 'double-tap' : 'hold shift and click on'} a box.</li> </ul> </div> <div className="new-box-area" onMouseEnter={this.addBox} onTouchStart={this.addBox} /> <TransitionMotion willEnter={() => ({opacity: 0, left: 0, top: 0})} willLeave={(lv) => ({...lv.styles, opacity: spring(0)})} styles={this.state.boxes.allIDs.map((id) => ({ key: id, style: { opacity: spring(1), left: spring(this.state.boxes.byID[id].left), top: spring(this.state.boxes.byID[id].top) } }))} > {instances => ( <div className="boxes"> {instances.map(inst => ( <Box key={inst.key} {...{...inst.style, id: inst.key}} handleMouseDown={this.handleMouseDown} handleTouchStart={this.handleTouchStart} /> ))} </div> )} </TransitionMotion> </div> ); } } render( <Container/>, document.getElementById('dragEl') );
node_modules/react-bootstrap/es/PaginationButton.js
darklilium/Factigis_2
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 elementType from 'react-prop-types/lib/elementType'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: elementType, className: React.PropTypes.string, eventKey: React.PropTypes.any, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, active: React.PropTypes.bool, onClick: React.PropTypes.func }; var defaultProps = { componentClass: SafeAnchor, active: false, disabled: false }; var PaginationButton = function (_React$Component) { _inherits(PaginationButton, _React$Component); function PaginationButton(props, context) { _classCallCheck(this, PaginationButton); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, active = _props2.active, disabled = _props2.disabled, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === SafeAnchor) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return React.createElement( 'li', { className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(Component, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return PaginationButton; }(React.Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; export default PaginationButton;
src/SparklinesLine.js
konsumer/react-sparklines
import React from 'react'; export default class SparklinesLine extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style } = this.props; const linePoints = points .map((p) => [p.x, p.y]) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: color || style.fill || 'slategray' }; return ( <g> <polyline points={fillPoints.join(' ')} style={fillStyle} /> <polyline points={linePoints.join(' ')} style={lineStyle} /> </g> ) } }
examples/universal/client/index.js
ggerrietts/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );