path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/layout/Footer.js
petertrotman/critrolemoments
import React from 'react'; const Footer = () => <p>Footer</p>; export default Footer;
src/svg-icons/notification/system-update.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSystemUpdate = (props) => ( <SvgIcon {...props}> <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z"/> </SvgIcon> ); NotificationSystemUpdate = pure(NotificationSystemUpdate); NotificationSystemUpdate.displayName = 'NotificationSystemUpdate'; NotificationSystemUpdate.muiName = 'SvgIcon'; export default NotificationSystemUpdate;
example/es6/index.js
romagny13/react-form-validation
import React, { Component } from 'react'; import { render } from 'react-dom'; import App from './components/App'; render(<App />, document.getElementById('app'));
examples/src/app.js
Amirus/react-autosuggest
require('./app.less'); import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Badges from './Badges/Badges'; import Examples from './Examples'; import Footer from './Footer/Footer'; import ForkMeOnGitHub from './ForkMeOnGitHub/ForkMeOnGitHub'; class App extends Component { render() { return ( <div> <h1>react-autosuggest</h1> <Badges /> <Examples /> <Footer /> <ForkMeOnGitHub user="moroshko" repo="react-autosuggest" /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app'));
frontend/jqwidgets/jqwidgets-react/react_jqxlayout.js
liamray/nexl-js
/* jQWidgets v5.7.2 (2018-Apr) Copyright (c) 2011-2018 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxLayout extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['contextMenu','height','layout','minGroupHeight','minGroupWidth','resizable','rtl','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxLayout(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxLayout('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxLayout(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; contextMenu(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('contextMenu', arg) } else { return JQXLite(this.componentSelector).jqxLayout('contextMenu'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('height', arg) } else { return JQXLite(this.componentSelector).jqxLayout('height'); } }; layout(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('layout', arg) } else { return JQXLite(this.componentSelector).jqxLayout('layout'); } }; minGroupHeight(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('minGroupHeight', arg) } else { return JQXLite(this.componentSelector).jqxLayout('minGroupHeight'); } }; minGroupWidth(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('minGroupWidth', arg) } else { return JQXLite(this.componentSelector).jqxLayout('minGroupWidth'); } }; resizable(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('resizable', arg) } else { return JQXLite(this.componentSelector).jqxLayout('resizable'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('rtl', arg) } else { return JQXLite(this.componentSelector).jqxLayout('rtl'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('theme', arg) } else { return JQXLite(this.componentSelector).jqxLayout('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxLayout('width', arg) } else { return JQXLite(this.componentSelector).jqxLayout('width'); } }; destroy() { JQXLite(this.componentSelector).jqxLayout('destroy'); }; loadLayout(Layout) { JQXLite(this.componentSelector).jqxLayout('loadLayout', Layout); }; refresh() { JQXLite(this.componentSelector).jqxLayout('refresh'); }; performRender() { JQXLite(this.componentSelector).jqxLayout('render'); }; saveLayout() { return JQXLite(this.componentSelector).jqxLayout('saveLayout'); }; render() { let id = 'jqxLayout' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
site/components/NavBar.js
numso/react-dnd
import React from 'react'; import { DOCS_DEFAULT, EXAMPLES_DEFAULT } from '../Constants'; import './NavBar.less'; const GITHUB_URL = 'https://github.com/gaearon/react-dnd'; const DOCS_LOCATION = DOCS_DEFAULT.location; const EXAMPLES_LOCATION = EXAMPLES_DEFAULT.location; export default class NavBar { render() { return ( <div className="NavBar"> <div className="NavBar-container"> <div className="NavBar-logo"> <a href="./" target="_self" className="NavBar-logoTitle">React <i>DnD</i></a> <p className="NavBar-logoDescription">Drag and Drop for React</p> </div> <div className="NavBar-item"> <a className="NavBar-link" href={DOCS_LOCATION} target="_self">Docs</a> <a className="NavBar-link" href={EXAMPLES_LOCATION} target="_self">Examples</a> <a className="NavBar-link" href={GITHUB_URL}>GitHub</a> </div> </div> </div> ); } }
src/Card/CardExpander.js
boldr/boldr-ui
/* eslint-disable react/prefer-stateless-function, no-unused-vars */ import React, { Component } from 'react'; import cn from 'classnames'; import Icon from '../Icons/Icon'; import contextTypes from './contextTypes'; /** * The CardExpander component is just a simple `IconButton` that * gets generated through the `Card`'s `contextTypes`. Props are not used * at all. * * Any component below a component that has this component inject into it * and has the prop `expandable={true}` will be toggleable when this is clicked. * * You can manually inject the `CardExpander` component yourself if you want to * use a component that is not a `CardActions` or a `CardTitle`. */ export default class CardExpander extends Component { static contextTypes = contextTypes; render() { const { expanded, onExpandClick, iconClassName, iconChildren, tooltipPosition, tooltipLabel, tooltipDelay, } = this.context; return ( <Icon className={cn('md-collapser md-collapser--card', { 'md-collapser--flipped': expanded, })} kind={!expanded ? 'chevron-down' : 'chevron-up'} color="#222" size="24px" onClick={onExpandClick} > {iconChildren} </Icon> ); } }
actor-apps/app-web/src/app/components/common/ConnectionState.react.js
chenbk85/actor-platform
import React from 'react'; import classnames from 'classnames'; import ConnectionStateStore from 'stores/ConnectionStateStore'; const getStateFromStore = () => { return { connectionState: ConnectionStateStore.getState() }; }; class ConnectionState extends React.Component { constructor(props) { super(props); this.state = getStateFromStore(); ConnectionStateStore.addChangeListener(this.onStateChange); } componentWillUnmount() { ConnectionStateStore.removeChangeListener(this.onStateChange); } onStateChange = () => { this.setState(getStateFromStore); }; render() { const { connectionState } = this.state; const className = classnames('connection-state', { 'connection-state--online': connectionState === 'online', 'connection-state--connection': connectionState === 'connecting' }); switch (connectionState) { case 'online': return ( <div className={className}>'You're back online!'</div> ); case 'connecting': return ( <div className={className}> Houston, we have a problem! Connection to Actor server is lost. Trying to reconnect now... </div> ); default: return null; } } } export default ConnectionState;
fields/types/cloudinaryimage/CloudinaryImageColumn.js
woody0907/keystone
import React from 'react'; import CloudinaryImageSummary from '../../components/columns/CloudinaryImageSummary'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; var CloudinaryImageColumn = React.createClass({ displayName: 'CloudinaryImageColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue: function() { var value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return; return ( <ItemsTableValue field={this.props.col.type}> <CloudinaryImageSummary label="dimensions" image={value} /> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = CloudinaryImageColumn;
src/components/rails/plain/RailsPlain.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './RailsPlain.svg' /** RailsPlain */ function RailsPlain({ width, height, className }) { return ( <SVGDeviconInline className={'RailsPlain' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } RailsPlain.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default RailsPlain
code/src/components/channelParameters.js
GreatDanton/Thesis
import React from 'react'; // custom imports import { InputBox } from './commonParts/inputBoxes.js'; import { ScatterChart } from './commonParts/charts.js'; import GlobalStorage from '../scripts/globalStorage'; class RectangularChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.rectangular; this.state = ({ h: this.storage.h, B: this.storage.B, ng: this.storage.ng, φ: this.storage.φ, P: this.storage.P, S: this.storage.S }); this.handleChange = this.handleChange.bind(this); } circumference() { let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let P = 2 * h + B; return P; } area() { let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let S = h * B; return S; } handleChange(event) { let id = event.target.id; let value = event.target.value; let calculateIf = ['B', 'h']; this.setState({ [id]: value }, function () { if (calculateIf.indexOf(id) > -1) { this.storage.S = this.area(); this.storage.P = this.circumference(); } }); this.storage[id] = value; } render() { return ( <div> <div className="container-900"> <div className="row"> <div className="col-30"> <InputBox id="B" end="m" value={this.state.B} onChange={this.handleChange} /> <InputBox id="h" end="m" value={this.state.h} onChange={this.handleChange} /> <br /> <InputBox id="ng" end="/" value={this.state.ng} onChange={this.handleChange} /> <InputBox id="φ" end="%" value={this.state.φ} onChange={this.handleChange} /> </div> <div className="col-70"> <img className="img-guide" src="images/rectangularChannel_guide.svg" alt="Rectangular river channel" /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> </div> ) } } class TrapezoidChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.trapezoid; this.state = ({ B: this.storage.B, b: this.storage.b, h: this.storage.h, ng: this.storage.ng, φ: this.storage.φ, S: this.storage.S, P: this.storage.P }); this.handleChange = this.handleChange.bind(this); } circumference() { let b = parseFloat(this.state.b); let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let x = (B - b) / 2 let P = b + 2 * (x ** 2 + h ** 2) ** (1 / 2); return P } area() { let b = parseFloat(this.state.b); let h = parseFloat(this.state.h); let B = parseFloat(this.state.B); let x = (B - b) / 2; let S = b * h + x * h return S } handleChange(event) { let value = event.target.value; let id = event.target.id; let calculateIf = ['B', 'b', 'h']; this.setState({ [id]: value }, function () { // callback function if (calculateIf.indexOf(id) > 0) { this.storage.S = this.area(); this.storage.P = this.circumference(); } }); this.storage[id] = value; // save value of input into global storage } render() { return ( <div> <div className="container-900"> <div className="row"> <div className="col-30"> <InputBox id="B" end="m" value={this.state.B} onChange={this.handleChange} /> <InputBox id="b" end="m" value={this.state.b} onChange={this.handleChange} /> <InputBox id="h" end="m" value={this.state.h} onChange={this.handleChange} /> <br /> <InputBox id="ng" end="/" value={this.state.ng} onChange={this.handleChange} /> <InputBox id="φ" end="%" value={this.state.φ} onChange={this.handleChange} /> </div> <div className="col-70"> <img className="img-guide" src="images/trapezoidChannel_guide.svg" alt="Trapezoid river channel" /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> </div> ) } } class CustomChannel extends React.Component { constructor(props) { super(props); this.storage = GlobalStorage.channelTab.custom; this.state = { points: this.storage.points, x: '', y: '', ng: this.storage.ng, φ: this.storage.φ }; this.onChange = this.onChange.bind(this); this.addPoint = this.addPoint.bind(this); this.deleteClick = this.deleteClick.bind(this); } // add new point to state addPoint(e) { e.preventDefault(); // if x & y are numbers, add them to the table let X = parseFloat(this.state.x); let Y = parseFloat(this.state.y); if (!isNaN(X) && !isNaN(Y)) { // if x and y is number let p = { x: X, y: Y }; let points = this.state.points.slice(); points.push(p); this.setState({ points: points, x: '', y: '' }); // add new array, and reset input fields this.storage.points = points; // save points array into storage } } onChange(e) { this.setState({ [e.target.id]: e.target.value }); if (e.target.id === "ng") { this.storage.ng = parseFloat(e.target.value); } else if (e.target.id === "φ") { this.storage.φ = parseFloat(e.target.value); } } deleteClick(e) { let id = e.currentTarget.getAttribute('id'); let pointsArr = this.state.points.slice(); // copy state pointsArr.splice(id, 1); // remove point with index same as id (clicked element) this.setState({ points: pointsArr }); this.storage.points = pointsArr; // save new array into global storage } render() { return ( <div className="container-900"> <div className="row"> <div className="col-30"> {/* button press on enter click will submit the form => execute addPoint*/} <form onSubmit={this.addPoint}> <div className="row centered"> <InputBox id="x" end="" value={this.state.x} onChange={this.onChange} /> <InputBox id="y" end="" value={this.state.y} onChange={this.onChange} /> </div> <div className="row centered"> <button type="submit" className="btn btn-primary"> Add </button> </div> </form> <div className="margin-u-40"> <InputBox id="ng" value={this.state.ng} onChange={this.onChange} end={"/"} /> <InputBox id="φ" value={this.state.φ} onChange={this.onChange} end={"%"} /> </div> <div className="row"> <PointsTable data={this.state.points} onClick={this.deleteClick} /> </div> </div> <div className="col-70 padding-h-20"> <ScatterChart name={["custom channel"]} data={[this.state.points]} pointBorder={'y'} /> <img className="img-level-guide" src="images/vertical_crossSection.svg" alt="River channel horizontal section" /> </div> </div> </div> ) } } // PointsTable component is used for displaying x,y points that define // custom river channel class PointsTable extends React.Component { render() { let TableRows = this.props.data.map((point, index) => { return ( <TableRow passIndex={index} x={point.x} y={point.y} key={index} onClick={this.props.onClick} /> ) }); return ( <table className="zebra"> <thead> <tr> <th> </th> <th className="padding-h-20"> x </th> <th className="padding-h-20"> y </th> </tr> </thead> <tbody> {TableRows} </tbody> </table> ) } } // TableRow is used to display one table row with x,y point coordinates // and x button that is used to delete the row. class TableRow extends React.Component { render() { return ( <tr> <td className="td-delete" onClick={this.props.onClick} x={this.props.x} y={this.props.y} id={this.props.passIndex}> × </td> <td className="padding-h-20"> {this.props.x} </td> <td className="padding-h-20"> {this.props.y} </td> </tr> ) } } export { RectangularChannel, TrapezoidChannel, CustomChannel };
public/js/components/user.js
AC287/wdi_final_arrowlense2.0_FE
import React from 'react' import {Link} from 'react-router' import Firebase from 'firebase' import InstructorView from './user_instructor' import StudentView from './user_student' const userRef = new Firebase('https://arrowlense2-0.firebaseio.com/'); const getUserInfo = new Firebase('https://arrowlense2-0.firebaseio.com/users'); export default React.createClass({ contextTypes: { user: React.PropTypes.string, userid: React.PropTypes.string, userinfo: React.PropTypes.object, router: React.PropTypes.object.isRequired, }, render: function() { // let { userRole } = this.props.params // console.log(this.context.userinfo); switch (this.context.userinfo.role) { case 'instructor': return ( <InstructorView/> ) break; case 'student': return( <StudentView/> ) break; default: return( <h3>Please log in to access this page.</h3> ) } } })
src/lib/ResizeGhost.js
maheshsenni/react-treelist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import '../css/resize-ghost.css'; class ResizeGhost extends Component { constructor(props) { super(props); this.displayName = 'ResizeGhost'; this.onMouseLeave = this.onMouseLeave.bind(this); this.onDragStart = this.onDragStart.bind(this); this.onDragEnd = this.onDragEnd.bind(this); this.documentDragoverHandler = this.documentDragoverHandler.bind(this); this.state = { resizing: false, dragX: 0 }; } onMouseLeave() { this.props.onLeave(); } onDragStart(event) { // setting 'event.dataTransfer' for firefox :( event.dataTransfer.setData('text', ''); this._initialX = event.clientX; this.props.onDragStart(event.clientX); } onDragEnd() { this.props.onDragEnd(); } documentDragoverHandler(event) { const movedX = event.clientX - this._initialX; this.props.onDrag(movedX); } componentDidMount() { document.addEventListener('dragover', this.documentDragoverHandler, false); } componentWillUnmount() { document.removeEventListener('dragover', this.documentDragoverHandler, false); } render() { return ( <div draggable='true' className='resize-handle' style={{...this.props}} onMouseLeave={this.onMouseLeave} onDragStart={this.onDragStart} onDragEnd={this.onDragEnd}></div> ); } } ResizeGhost.propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, top: PropTypes.number.isRequired, left: PropTypes.number.isRequired, onLeave: PropTypes.func.isRequired, onDragStart: PropTypes.func.isRequired, onDrag: PropTypes.func.isRequired, onDragEnd: PropTypes.func.isRequired }; export default ResizeGhost;
client/admin/info/RocketChatSection.stories.js
iiet/iiet-chat
import React from 'react'; import { dummyDate } from '../../../.storybook/helpers'; import { RocketChatSection } from './RocketChatSection'; export default { title: 'admin/info/RocketChatSection', component: RocketChatSection, decorators: [ (fn) => <div className='rc-old'>{fn()}</div>, ], }; const info = { marketplaceApiVersion: 'info.marketplaceApiVersion', }; const statistics = { version: 'statistics.version', migration: { version: 'statistics.migration.version', lockedAt: dummyDate, }, installedAt: dummyDate, process: { uptime: 10 * 24 * 60 * 60, pid: 'statistics.process.pid', }, uniqueId: 'statistics.uniqueId', instanceCount: 1, oplogEnabled: true, }; export const _default = () => <RocketChatSection info={info} statistics={statistics} />; export const loading = () => <RocketChatSection info={{}} statistics={{}} isLoading />;
packages/material-ui-icons/src/AccountBox.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z" /></g> , 'AccountBox');
react/features/invite/components/PasswordContainer.js
KalinduDN/kalindudn.github.io
import React, { Component } from 'react'; import { translate } from '../../base/i18n'; import { LOCKED_LOCALLY } from '../../room-lock'; import AddPasswordForm from './AddPasswordForm'; import LockStatePanel from './LockStatePanel'; import RemovePasswordForm from './RemovePasswordForm'; /** * React {@code Component} for displaying the current room lock state as well as * exposing features to modify the room lock. */ class PasswordContainer extends Component { /** * {@code PasswordContainer}'s property types. * * @static */ static propTypes = { /** * The JitsiConference for which to display a lock state and change the * password. * * @type {JitsiConference} */ conference: React.PropTypes.object, /** * The value for how the conference is locked (or undefined if not * locked) as defined by room-lock constants. */ locked: React.PropTypes.string, /** * The current known password for the JitsiConference. */ password: React.PropTypes.string, /** * Whether or not the password editing components should be displayed. */ showPasswordEdit: React.PropTypes.bool, /** * Invoked to obtain translated strings. */ t: React.PropTypes.func }; /** * Initializes a new {@code PasswordContainer} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props) { super(props); this.state = { /** * Whether or not the form to edit the password should display. If * true, the form should display. * * @type {boolean} */ isEditingPassword: false }; // Bind event handlers so they are only bound once for every instance. this._onTogglePasswordEdit = this._onTogglePasswordEdit.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <div className = 'password-overview'> <div className = 'password-overview-status'> <LockStatePanel locked = { Boolean(this.props.locked) } /> { this._renderShowPasswordLink() } </div> { this._renderPasswordEdit() } </div> ); } /** * Toggles the display of the ReactElements used to edit the password. * * @private * @returns {void} */ _onTogglePasswordEdit() { this.setState({ isEditingPassword: !this.state.isEditingPassword }); } /** * Creates a ReactElement used for setting or removing a password. * * @private * @returns {ReactElement|null} */ _renderPasswordEdit() { if (!this.state.isEditingPassword) { return null; } return ( this.props.locked ? <RemovePasswordForm conference = { this.props.conference } lockedLocally = { this.props.locked === LOCKED_LOCALLY } password = { this.props.password } /> : <AddPasswordForm conference = { this.props.conference } /> ); } /** * Creates a ReactElement that toggles displaying password edit components. * * @private * @returns {ReactElement|null} */ _renderShowPasswordLink() { if (!this.props.showPasswordEdit) { return null; } let toggleStatusKey; if (this.state.isEditingPassword) { toggleStatusKey = 'invite.hidePassword'; } else if (this.props.locked) { toggleStatusKey = 'invite.showPassword'; } else { toggleStatusKey = 'invite.addPassword'; } return ( <a className = 'password-overview-toggle-edit' onClick = { this._onTogglePasswordEdit }> { this.props.t(toggleStatusKey) } </a> ); } } export default translate(PasswordContainer);
src/layouts/layout-5-2.js
binary-com/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className} onClick={onClick}> <div className="vertical"> {components[0]} {components[1]} {components[2]} {components[3]} </div> <div className="vertical"> {components[4]} </div> </div> );
app/component/app.js
caoqianjie/react-webpack-demo1
import $ from 'jquery'; import NewsList from './NewsList' import React from 'react'; import { render } from 'react-dom'; import '../src/css/app.css'; function get(url) { return Promise.resolve($.get(url)); } get('https://hacker-news.firebaseio.com/v0/topstories.json') .then(function (stories) { return Promise.all(stories.slice(0,30).map(itemId => get('https://hacker-news.firebaseio.com/v0/item/'+itemId+'.json'))); }) .then(function (items) { render(<NewsList items={items}/>,$('#app')[0]); }) .catch(function (err) { console.log('err occur', err); });
app/containers/PrototypeSearch/header.js
mhoffman/CatAppBrowser
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import ReactGA from 'react-ga'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import { withStyles } from 'material-ui/styles'; import { styles } from './styles'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <Grid container direction="row" justify="space-between"> <Grid item> <h1>Prototype Search</h1> </Grid> <Grid item> <Link to={'/catKitDemo'} className={this.props.classes.outboundLink} > <Button raised className={this.props.classes.publicationAction} > CatKit Slab Generator </Button> </Link> </Grid> <Grid> <div className={this.props.classes.infoText} >Powered by <ReactGA.OutboundLink eventLabel="https://gitlab.com/ankitjainmeiitk/Enumerator" to="https://gitlab.com/ankitjainmeiitk/Enumerator" target="_blank" > gitlab/ankitjainmeiitk/Enumerator </ReactGA.OutboundLink> </div> </Grid> </Grid> ); } } Header.propTypes = { classes: PropTypes.object, }; export default withStyles(styles, { withTheme: true })(Header);
app/javascript/mastodon/features/ui/components/compose_panel.js
tateisu/mastodon
import React from 'react'; import SearchContainer from 'mastodon/features/compose/containers/search_container'; import ComposeFormContainer from 'mastodon/features/compose/containers/compose_form_container'; import NavigationContainer from 'mastodon/features/compose/containers/navigation_container'; import LinkFooter from './link_footer'; const ComposePanel = () => ( <div className='compose-panel'> <SearchContainer openInRoute /> <NavigationContainer /> <ComposeFormContainer singleColumn /> <LinkFooter withHotkeys /> </div> ); export default ComposePanel;
imports/ui/admin/components/.stories/contact.js
dououFullstack/atomic
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { setComposerStub } from 'react-komposer'; import Contact from '../contact.jsx'; storiesOf('admin.Contact', module) .add('default view', () => { return ( <Contact /> ); })
src/cardPage.js
henyouqian/sale
import React, { Component } from 'react'; import { render } from 'react-dom'; import { SideMenu } from './sideMenu'; import FastClick from "fastclick"; import * as lwUtil from "./lwUtil" import $ from "jquery" import "velocity-animate" import { Dlg, DlgAlert } from"./dlg" // require("./cardPage.css"); let _rootEl = document.getElementById("root"); FastClick.attach(_rootEl); let _state = { card:{}, editable:lwUtil.getUrlParam("editable")?true:false } class CardPage extends Component { componentDidMount(){ var msg = { UserId:-1, } if (!_state.editable) { msg.UserId = parseInt(lwUtil.getUrlParam("userId")) if (!msg.UserId) { alert("need userId param") return } } lwUtil.post("catalog/getCard", msg).then(resp=>{ console.log(resp) if (resp.Card){ _state.card = JSON.parse(resp.Card) Object.keys(_state.card).forEach(k=>{ let ref = this.refs[k] if (ref) { ref.setState({"value": _state.card[k]}) } }) } }, err=>{ console.error(err) }) } render() { const card = _state.card let inputUIs = [ {key:"Company", label:"企业", icon:"building-o", placeholder:"必填"}, {key:"ContactPerson", label:"联系人", icon:"user", placeholder:"必填"}, {key:"Phone", label:"电话", icon:"phone", placeholder:"必填"}, {key:"Email", label:"邮箱", icon:"envelope-o"}, {key:"Weixin", label:"微信", icon:"wechat"} ] const editable = _state.editable let inputEls = inputUIs.map(v=>{ return <Input key={v.key} label={v.label} icon={v.icon} ref={v.key} placeholder={v.placeholder} editable={editable}/> }) const title = editable?"编辑我的联系方式":"供货商联系方式" const btn = editable?<button className="uk-button uk-button-large .uk-width-1-1" onClick={()=>this._onSave()}><i className="uk-icon-save"></i> 保存</button>:"" return ( <div className="uk-container uk-container-center"> <div className="uk-width-1-1" style={{maxWidth:"720px", margin:"15px auto"}}> <div className="uk-panel uk-panel-box widget_text"> <div className="uk-panel-badge uk-badge tm-badge-primary" data-uk-offcanvas="{target:'#offcanvas'}" style={{left:0, right:"auto"}}> <a href="#offcanvas" data-uk-offcanvas className="uk-icon-navicon" style={{color:"white"}}></a> </div> <SideMenu /> <div className="uk-panel-teaser"> <img src="/home_venice.jpg" width="722" height="407" alt=""/> </div> <h2>{title}</h2> <div> <form className="uk-form uk-form-stacked"> {inputEls} </form> </div> </div> {btn} </div> <div style={{height:"40px"}}></div> <DlgAlert ref="dlg" title="保存成功" msg=""></DlgAlert> </div> ); } _onSave() { let d = React.createElement(Dlg) console.log(d) // this.refs.dlg.show() // this.forceUpdate() const props = ["Company", "ContactPerson", "Phone", "Email", "Weixin"] const requiredProps = ["Company", "ContactPerson", "Phone"] let ok = true const card = props.reduce((r,k)=>{ let v = r[k] = this.refs[k].state.value; if (v.length == 0 && requiredProps.indexOf(k)>=0) { this.refs[k].setState({err: true}) ok = false } else { this.refs[k].setState({err: false}) } return r }, {}) if (ok){ this.props.onSave(card) lwUtil.post("catalog/editCard", card).then(resp=>{ console.log(resp) _state.card = card this.refs.dlg.show() }, err=>{ console.error(err) }) } } } class Input extends Component { constructor(props) { super(props) this.state = {err: false, value:""} } render() { let type = this.props.type?this.props.type:"text" let style = this.state.err?{border:"1px solid red"}:{} let placeholder = this.props.placeholder || "" let value = this.state.value let input = this.props.editable? <input className="uk-width-1-1 uk-form-large" type={type} style={style} placeholder={placeholder} ref="input" value={value} onChange={e=>{this.onChange(e)}}/> :<input disabled className="uk-width-1-1 uk-form-large" type={type} style={style} placeholder={placeholder} ref="input" value={value} onChange={e=>{this.onChange(e)}}/> return ( <div className="uk-form-row"> <label className="uk-form-label">{this.props.label}</label> <div className="uk-form-controls"> <div className="uk-form-icon uk-width-1-1"> <i className={"uk-icon-"+this.props.icon}></i> {input} </div> </div> </div> ) } onChange(e){ if (this.props.editable) { this.setState({value: e.target.value}) } } // render() { // var value = this.state.value; // return <input type="text" value={value} onChange={event=>{this.setState({value: event.target.value})}} />; // } } render(<div><CardPage onSave={(info) => console.log("onSave", info)}/></div>, document.getElementById('root')); let loadState = lwUtil.hisOnload() console.log(loadState)
docs/app/Examples/elements/Label/Types/LabelExampleFloating.js
mohammed88/Semantic-UI-React
import React from 'react' import { Icon, Label, Menu } from 'semantic-ui-react' const LabelExampleFloating = () => ( <Menu compact> <Menu.Item as='a'> <Icon name='mail' /> Messages <Label color='red' floating>22</Label> </Menu.Item> <Menu.Item as='a'> <Icon name='users' /> Friends <Label color='teal' floating>22</Label> </Menu.Item> </Menu> ) export default LabelExampleFloating
src/views/components/SettingValue.js
physiii/home-gateway
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; export const SettingValue = (props) => { let formatted; switch (props.type) { case 'percentage': formatted = Math.round(props.children * 100) + '%'; break; case 'time-of-day': formatted = moment.utc(props.children).format('h:mm A'); break; default: formatted = props.children; break; } return <React.Fragment>{formatted}</React.Fragment>; }; SettingValue.propTypes = { type: PropTypes.string, children: PropTypes.any }; export default SettingValue;
js/jqwidgets/demos/react/app/dockinglayout/righttoleftlayout/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDockingLayout from '../../../jqwidgets-react/react_jqxdockinglayout.js'; import JqxTree from '../../../jqwidgets-react/react_jqxtree.js'; class App extends React.Component { render() { let layout = [{ type: 'layoutGroup', orientation: 'horizontal', items: [{ type: 'autoHideGroup', alignment: 'left', width: 80, unpinnedWidth: 200, items: [{ type: 'layoutPanel', title: 'Toolbox', contentContainer: 'ToolboxPanel' }, { type: 'layoutPanel', title: 'Help', contentContainer: 'HelpPanel' }] }, { type: 'layoutGroup', orientation: 'vertical', width: 500, items: [{ type: 'documentGroup', height: 400, minHeight: 200, items: [{ type: 'documentPanel', title: 'Document 1', contentContainer: 'Document1Panel' }, { type: 'documentPanel', title: 'Document 2', contentContainer: 'Document2Panel' }] }, { type: 'tabbedGroup', height: 200, pinnedHeight: 30, items: [{ type: 'layoutPanel', title: 'Error List', contentContainer: 'ErrorListPanel' }] }] }, { type: 'tabbedGroup', width: 220, minWidth: 200, items: [{ type: 'layoutPanel', title: 'Solution Explorer', contentContainer: 'SolutionExplorerPanel', initContent: () => { // initialize a jqxTree inside the Solution Explorer Panel let source = [{ icon: '../../../images/earth.png', label: 'Project', expanded: true, items: [{ icon: '../../../images/folder.png', label: 'css', expanded: true, items: [{ icon: '../../../images/nav1.png', label: 'jqx.base.css' }, { icon: '../../../images/nav1.png', label: 'jqx.energyblue.css' }, { icon: '../../../images/nav1.png', label: 'jqx.orange.css' }] }, { icon: '../../../images/folder.png', label: 'scripts', items: [{ icon: '../../../images/nav1.png', label: 'jqxcore.js' }, { icon: '../../../images/nav1.png', label: 'jqxdata.js' }, { icon: '../../../images/nav1.png', label: 'jqxgrid.js' }] }, { icon: '../../../images/nav1.png', label: 'index.htm' }] }]; ReactDOM.render( <JqxTree style={{ border: 'none' }} width={190} source={source} rtl={true} /> , document.getElementById('solutionExplorerTree')); } }, { type: 'layoutPanel', title: 'Properties', contentContainer: 'PropertiesPanel' }] }] }, { type: 'floatGroup', width: 500, height: 300, position: { x: 350, y: 250 }, items: [{ type: 'layoutPanel', title: 'Output', contentContainer: 'OutputPanel', selected: true }] }]; return ( <JqxDockingLayout width={800} height={600} layout={layout} rtl={true}> <div data-container="ToolboxPanel"> List of tools </div> <div data-container="HelpPanel"> Help topics </div> <div data-container="Document1Panel"> Document 1 content </div> <div data-container="Document2Panel"> Document 2 content </div> <div data-container="ErrorListPanel"> List of errors </div> <div data-container="SolutionExplorerPanel"> <div id="solutionExplorerTree" /> </div> <div data-container="PropertiesPanel"> List of properties </div> <div data-container="OutputPanel"> <div style={{ fontFamily: 'Consolas' }}> <p> Themes installation complete. </p> <p> List of installed stylesheet files. Include at least one stylesheet Theme file and the images folder: </p> <ul> <li>styles/jqx.base.css: Stylesheet for the base Theme. The jqx.base.css file should be always included in your project.</li> <li>styles/jqx.arctic.css: Stylesheet for the Arctic Theme</li> <li>styles/jqx.web.css: Stylesheet for the Web Theme</li> <li>styles/jqx.bootstrap.css: Stylesheet for the Bootstrap Theme</li> <li>styles/jqx.classic.css: Stylesheet for the Classic Theme</li> <li>styles/jqx.darkblue.css: Stylesheet for the DarkBlue Theme</li> <li>styles/jqx.energyblue.css: Stylesheet for the EnergyBlue Theme</li> <li>styles/jqx.shinyblack.css: Stylesheet for the ShinyBlack Theme</li> <li>styles/jqx.office.css: Stylesheet for the Office Theme</li> <li>styles/jqx.metro.css: Stylesheet for the Metro Theme</li> <li>styles/jqx.metrodark.css: Stylesheet for the Metro Dark Theme</li> <li>styles/jqx.orange.css: Stylesheet for the Orange Theme</li> <li>styles/jqx.summer.css: Stylesheet for the Summer Theme</li> <li>styles/jqx.black.css: Stylesheet for the Black Theme</li> <li>styles/jqx.fresh.css: Stylesheet for the Fresh Theme</li> <li>styles/jqx.highcontrast.css: Stylesheet for the HighContrast Theme</li> <li>styles/jqx.blackberry.css: Stylesheet for the Blackberry Theme</li> <li>styles/jqx.android.css: Stylesheet for the Android Theme</li> <li>styles/jqx.mobile.css: Stylesheet for the Mobile Theme</li> <li>styles/jqx.windowsphone.css: Stylesheet for the Windows Phone Theme</li> <li>styles/jqx.ui-darkness.css: Stylesheet for the UI Darkness Theme</li> <li>styles/jqx.ui-lightness.css: Stylesheet for the UI Lightness Theme</li> <li>styles/jqx.ui-le-frog.css: Stylesheet for the UI Le Frog Theme</li> <li>styles/jqx.ui-overcast.css: Stylesheet for the UI Overcast Theme</li> <li>styles/jqx.ui-redmond.css: Stylesheet for the UI Redmond Theme</li> <li>styles/jqx.ui-smoothness.css: Stylesheet for the UI Smoothness Theme</li> <li>styles/jqx.ui-start.css: Stylesheet for the UI Start Theme</li> <li>styles/jqx.ui-sunny.css: Stylesheet for the UI Sunny Theme</li> <li>styles/images: contains images referenced in the stylesheet files</li> </ul> </div> </div> </JqxDockingLayout> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/index.js
w01fgang/react-static-boilerplate
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React from 'react'; export default class { render() { return ( <div> <h1>Home Page</h1> <p>Coming soon.</p> </div> ); } };
examples/official-storybook/components/DocgenButton.js
storybooks/react-storybook
import React from 'react'; import PropTypes from 'prop-types'; /** * DocgenButton component description imported from comments inside the component file, * * *Important Note*: Unlike with normal `<input>` elements, setting this will * not validate the input contents. This is because in this project we use * Formik and Yup to validate fields at the form-level, not at the individual * input level. It is still very important to set this value properly for * accessibility and user experience. * * Here's a list to test out formatting. * * * `"number"` Any number not represented by a more specific type. * * `"password"` A password. * * `"email"` An email address. * * `"tel"` A phone or fax number. Shows the phone number keypad on * mobile keyboards. */ export const DocgenButton = ({ disabled, label, onClick }) => ( <button type="button" disabled={disabled} onClick={onClick}> {label} </button> ); DocgenButton.defaultProps = { disabled: false, onClick: () => {}, optionalString: 'Default String', one: { key: 1 }, two: { thing: { id: 2, func: () => {}, arr: [], }, }, obj: { key: 'value', }, shape: { id: 3, func: () => {}, arr: [], shape: { shape: { foo: 'bar', }, }, }, arrayOf: [1, 2, 3], msg: new Set(), enm: 'News', enmEval: 'Photos', union: 'hello', }; /* eslint-disable react/no-unused-prop-types */ DocgenButton.propTypes = { /** Boolean indicating whether the button should render as disabled */ disabled: PropTypes.bool, /** button label. */ label: PropTypes.string.isRequired, /** onClick handler */ onClick: PropTypes.func, /** * A simple `objectOf` propType. */ one: PropTypes.objectOf(PropTypes.number), /** * A very complex `objectOf` propType. */ two: PropTypes.objectOf( PropTypes.shape({ /** * Just an internal propType for a shape. * It's also required, and as you can see it supports multi-line comments! */ id: PropTypes.number.isRequired, /** * A simple non-required function */ func: PropTypes.func, /** * An `arrayOf` shape */ arr: PropTypes.arrayOf( PropTypes.shape({ /** * 5-level deep propType definition and still works. */ index: PropTypes.number.isRequired, }) ), }) ), /** * Plain object propType (use shape!!) */ obj: PropTypes.object, // eslint-disable-line react/forbid-prop-types /** * propType for shape with nested arrayOf * * Also, multi-line description */ shape: PropTypes.shape({ /** * Just an internal propType for a shape. * It's also required, and as you can see it supports multi-line comments! */ id: PropTypes.number.isRequired, /** * A simple non-required function */ func: PropTypes.func, /** * An `arrayOf` shape */ arr: PropTypes.arrayOf( PropTypes.shape({ /** * 5-level deep propType definition and still works. */ index: PropTypes.number.isRequired, }) ), shape: PropTypes.shape({ shape: PropTypes.shape({ foo: PropTypes.string, }), }), }), /** * array of a certain type */ arrayOf: PropTypes.arrayOf(PropTypes.number), /** * `instanceOf` is also supported and the custom type will be shown instead of `instanceOf` */ msg: PropTypes.instanceOf(Set), /** * `oneOf` is basically an Enum which is also supported but can be pretty big. * * Testing a list: * * - `News` first * - `Photos` second */ enm: PropTypes.oneOf(['News', 'Photos']), enmEval: PropTypes.oneOf((() => ['News', 'Photos'])()), /** * A multi-type prop is also valid and is displayed as `Union<String|Message>` */ union: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Set)]), /** * test string with a comment that has * two identical lines * two identical lines */ optionalString: PropTypes.string, };
app/javascript/mastodon/features/ui/components/columns_area.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import HomeTimeline from '../../home_timeline'; import Notifications from '../../notifications'; import PublicTimeline from '../../public_timeline'; import CommunityTimeline from '../../community_timeline'; import HashtagTimeline from '../../hashtag_timeline'; import Compose from '../../compose'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, }; class ColumnsArea extends ImmutablePureComponent { static propTypes = { columns: ImmutablePropTypes.list.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; render () { const { columns, children, singleColumn } = this.props; if (singleColumn) { return ( <div className='columns-area'> {children} </div> ); } return ( <div className='columns-area'> {columns.map(column => { const SpecificComponent = componentMap[column.get('id')]; const params = column.get('params', null) === null ? null : column.get('params').toJS(); return <SpecificComponent key={column.get('uuid')} columnId={column.get('uuid')} params={params} multiColumn />; })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } } export default ColumnsArea;
tests/Rules-isUrl-spec.js
bitgaming/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations="isUrl" value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'should pass with default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with "foo"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="foo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with "https://www.google.com/"': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue="https://www.google.com/"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with an empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); } };
src/frontend/src/components/GMDataList.js
blengerich/GenAMap
import React from 'react' import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table' import fetch from './fetch' import config from '../../config' const GMDataTable = React.createClass({ render: function () { const data = this.props.data.map((row, i) => { return ( <TableRow key={i} selectable={false}> { row.split(',').map((entry, j) => <TableRowColumn key={j}>{entry}</TableRowColumn> ) } </TableRow> ) }) const headers = this.props.headers.map((columnName, i) => <TableHeaderColumn key={i}>{columnName}</TableHeaderColumn> ) return ( <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> {headers} </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {data} </TableBody> </Table> ) } }) const GMDataList = React.createClass({ getInitialState: function () { return {data: [], headers: [], title: ''} }, componentDidMount: function () { this.loadData(this.props.params.id) }, loadData: function (id) { let dataRequest = { method: 'GET', headers: { 'Content-Type': 'application/json' } } fetch(`${config.api.dataUrl}/${id}`, dataRequest) .then(response => response.json().then(json => ({ json, response }))) .then(({ json, response }) => { if (!response.ok) { this.setState({ title: json.message, data: undefined }) Promise.reject(json.message) } else { const data = json.data.split('\n') const headers = data[0].split(',') data.splice(0, 1) this.setState({ title: json.file.name, data, headers }) } }).catch(err => console.log('Error: ', err)) }, componentWillReceiveProps: function (nextProps) { this.loadData(nextProps.params.id) }, render: function () { return this.state.data ? ( <div> <h1>{this.state.title}</h1> <GMDataTable data={this.state.data} headers={this.state.headers} /> </div> ) : ( <div> <h1>{this.state.title}</h1> </div> ) } }) export default GMDataList
client/src/components/Profile/Inbox/Inbox.js
wolnewitz/raptor-ads
import React, { Component } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { Container, Header, Loader } from 'semantic-ui-react'; import { getAllReceivedMessages } from '../../../actions/inboxActions'; import MessagesTable from './MessagesTable'; import { changeContactField, sendMessage } from '../../../actions/fullListingActions'; import { clearErrors } from '../../../actions/listingActions'; class Inbox extends Component { constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.convertTime = this.convertTime.bind(this); } componentDidMount() { this.props.dispatch(getAllReceivedMessages(this.props.userId)); } onSubmit(e, listingId, userId, senderId) { e.preventDefault(); const data = this.props.contactForm; const postId = listingId; const payload = { title: data.title, body: data.body, postId, userId, senderId }; this.props.dispatch(clearErrors()); this.props.dispatch(sendMessage(payload)); } onChange(e, data) { if (data) { this.props.dispatch(changeContactField('type', data.value)); } else { this.props.dispatch(changeContactField(e.target.name, e.target.value)); } } convertTime(time) { return moment(time).fromNow(); } render() { const { isFetching, allMessages } = this.props; if (isFetching) { return <Loader active inline="centered" />; } return ( <Container textAlign="center"> <Header as="h1" className="center">-- Inbox -- <br /></Header> <Container textAlign="left"> <MessagesTable allMessages={allMessages} convertTime={this.convertTime} onChange={this.onChange} onSubmit={this.onSubmit} /> </Container> </Container> ); } } const mapStateToProps = (state) => { const { contactForm } = state.messages; const { isFetching, allMessages } = state.inbox; const { id } = state.auth.loggedInUser; return { allMessages, isFetching, contactForm, }; }; Inbox.propTypes = { userId: React.PropTypes.number.isRequired, isFetching: React.PropTypes.bool.isRequired, contactForm: React.PropTypes.object.isRequired, allMessages: React.PropTypes.array.isRequired, dispatch: React.PropTypes.func.isRequired, }; export default connect(mapStateToProps)(Inbox);
client/pages/examples/advanced/winds/index.js
fdesjardins/webgl
import React from 'react' import PT from 'prop-types' import * as THREE from 'three' import Promise from 'bluebird' import droidSans from '-/assets/fonts/helvetiker_bold.typeface.json' import Example from '-/components/example' import notes from './readme.md' import stationsData from './stations.json' import threeOrbitControls from 'three-orbit-controls' const globals = { stations: [], particles: { vertices: [], }, fontLoader: new THREE.FontLoader(), font: null, colors: { stations: 0x4466ff, stationLabels: 0xffffff, }, } /** * Create a station mesh object */ const createStation = (station) => { const stationGeom = new THREE.IcosahedronBufferGeometry(0.35, 0) const stationMat = new THREE.MeshPhongMaterial({ color: globals.colors.stations, }) const polyhedron = new THREE.Mesh(stationGeom, stationMat) const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30) polyhedron.position.set(...pos) return polyhedron } /** * Create a station mesh label */ const createStationLabel = (station) => { const textMat = new THREE.MeshPhongMaterial({ color: globals.colors.stationLabels, }) const defaultTextBufferGeomOpts = { size: 0.25, height: 0.25, curveSegments: 3, bevelEnabled: false, } const textGeom = new THREE.TextBufferGeometry( station.stationName, Object.assign({}, defaultTextBufferGeomOpts, { font: globals.font, }) ) const text = new THREE.Mesh(textGeom, textMat) const pos = calcPosFromLatLonRad(station.latitude, station.longitude, 30) text.position.set(...pos) return text } /** * Load the stations data into the given scene */ const loadStations = async (scene) => { const font = globals.fontLoader.parse(droidSans) globals.font = font const loadStations = stationsData.stations.map((s) => async () => { const station = createStation(s) const label = createStationLabel(s) scene.add(station) scene.add(label) globals.stations.push(station) }) Promise.map(loadStations, (x) => Promise.resolve(x()).delay(100), { concurrency: 25, }) } const loadParticles = async (scene) => { const particleCount = 1800 const particleGeom = new THREE.Geometry() const particleMat = new THREE.PointsMaterial({ color: 0xffffff, size: 0.5, }) Array.from(new Array(particleCount).keys()).forEach(() => { const x = Math.random() * 150 - 75 const y = Math.random() * 100 - 50 const particle = new THREE.Vector3(x, y, 0) particleGeom.vertices.push(particle) }) globals.particles = particleGeom const particles = new THREE.Points(particleGeom, particleMat) scene.add(particles) } /** * didMount() */ const init = ({ canvas }) => { console.log(canvas) // Create the scene and renderer const scene = new THREE.Scene() const renderer = new THREE.WebGLRenderer({ canvas }) renderer.setSize(canvas.clientWidth, canvas.clientHeight) // Add the camera const camera = new THREE.PerspectiveCamera( 75, canvas.clientWidth / canvas.clientHeight, 1, 100000 ) camera.position.z = 50 const OrbitControls = threeOrbitControls(THREE) const controls = new OrbitControls(camera) controls.update() // Add the main light source const light = new THREE.PointLight(0xffffff, 2, 200) light.position.set(0, 40, 40) scene.add(light) let frame = 0 const animate = () => { requestAnimationFrame(animate) globals.stations.forEach((p, i) => { p.rotation.x += 0.01 }) controls.update() globals.particles.vertices.forEach((p, i) => { const newPos = updateParticlePosition(p, frame) p.x = newPos.x p.y = newPos.y }) globals.particles.verticesNeedUpdate = true renderer.render(scene, camera) frame += 0.1 } animate() loadStations(scene) loadParticles(scene) return () => { scene.dispose() renderer.dispose() } } const updateParticlePosition = (pos, frame) => { const [x, y, z] = [ pos.x + (Math.random() - 0.5) * 0.2, pos.y + (Math.random() - 0.5) * 0.2, pos.z, ] return new THREE.Vector3(x, y, z) } /** * Calculate a 3D position from a lat,lng pair and radius. */ // const calc3dPosFromLatLonRad = (lat, lon, radius) => { // const phi = (90 - lat) * (Math.PI / 180) // const theta = (lon + 180) * (Math.PI / 180) // // const x = -(radius * Math.sin(phi) * Math.cos(theta)) // const z = radius * Math.sin(phi) * Math.sin(theta) // const y = radius * Math.cos(phi) // // return [x, y, z] // } /** * Calculate a 3D position from a lat,lng pair and radius */ const calcPosFromLatLonRad = (lat, lon, radius) => { const shift = Math.PI * radius const x = (lon * shift) / 180 let y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180) y = (y * shift) / 180 return [x, y, 0] } const Winds = ({ color, id }) => { const canvas = React.useRef(null) console.log('effect') React.useEffect(() => { return init({ canvas: canvas.current }) }) return <canvas ref={canvas} /> } Winds.propTypes = { color: PT.string, id: PT.string, } const E = () => ( <div id="container"> <Example notes={notes} components={{ Winds }} init={() => () => {}} /> </div> ) export default E
src/js/Components/Common/BackgroundContent.js
mattgordils/DropSplash
import React, { Component } from 'react'; import 'sass/components/common/backgrounds'; export default class App extends Component { render () { var backgroundStyle = { backgroundImage: 'url(' + this.props.backgroundImage + ')' } var overlayStyle = { backgroundColor: this.props.overlayColor, opacity: this.props.overlayOpacity } var overlay = (<span className="bg-overlay" style={overlayStyle}></span>); return ( <div className="background-content" style={backgroundStyle}> {overlay} </div> ); } }
src/features/DocumentationModal/NavBar.js
erhathaway/cellular_automata
import React from 'react'; import styled from 'react-emotion'; const Container = styled('nav')` width: 100%; height: 80px; background-color: #252525; z-index: 999; display: flex; align-items: center; justify-content: flex-start; padding-left: 20px; @media (max-width: 500px) { height: 50px; } @media (min-width: 800px) { display: none; } `; export default ({ children }) => { return ( <Container> { children } </Container> ); };
modules/gui/src/app/home/body/process/recipe/classChange/panels/legend/legend.js
openforis/sepal
import {Form} from 'widget/form/form' import {Layout} from 'widget/layout' import {LegendBuilder, defaultColor} from 'app/home/map/legendBuilder' import {Panel} from 'widget/panel/panel' import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel' import {compose} from 'compose' import {msg} from 'translate' import {recipeActionBuilder} from 'app/home/body/process/recipe' import {selectFrom} from 'stateUtils' import {withRecipe} from 'app/home/body/process/recipeContext' import PropTypes from 'prop-types' import React from 'react' import _ from 'lodash' import guid from 'guid' import styles from './legend.module.css' const fields = { invalidEntries: new Form.Field() .predicate(invalid => !invalid, 'invalid'), entries: new Form.Field() .predicate((entries, {invalidEntries}) => !invalidEntries && entries.length, 'invalid') } const mapRecipeToProps = recipe => { return ({ toImage: selectFrom(recipe, 'model.toImage'), legendEntries: selectFrom(recipe, 'model.legend.entries') || [], fromImage: selectFrom(recipe, 'model.fromImage') }) } class _Legend extends React.Component { render() { const {legendEntries} = this.props return <LegendPanel legendEntries={legendEntries}/> } componentDidUpdate(prevProps) { const {fromImage: prevFromImage, toImage: prevToImage} = prevProps const {fromImage, toImage} = this.props if (!_.isEqual([prevFromImage, prevToImage], [fromImage, toImage])) { this.updateLegend() } } updateLegend() { const {recipeId, fromImage, toImage} = this.props if (!fromImage || !toImage) { return } const entries = fromImage.legendEntries .map(({label: fromLabel}) => toImage.legendEntries.map(({label: toLabel}) => { return `${fromLabel} -> ${toLabel}` }) ) .flat() .map((label, i) => ({ id: guid(), value: i + 1, color: defaultColor(i + 1), label })) const actionBuilder = recipeActionBuilder(recipeId) actionBuilder('UPDATE_LEGEND', {fromImage, toImage, entries}) .set('model.legend.entries', entries) .dispatch() } } class _LegendPanel extends React.Component { render() { return ( <RecipeFormPanel placement="bottom-right" className={styles.panel}> <Panel.Header icon="list" title={msg('process.classification.panel.legend.title')} /> <Panel.Content scrollable={false}> <Layout spacing='compact'> {this.renderContent()} </Layout> </Panel.Content> <Form.PanelButtons/> </RecipeFormPanel> ) } renderContent() { const {inputs: {entries}} = this.props return ( <LegendBuilder entries={entries.value} locked={true} onChange={(updatedEntries, invalid) => this.updateLegendEntries(updatedEntries, invalid)} /> ) } componentDidMount() { const {legendEntries, inputs} = this.props inputs.entries.set(legendEntries) } updateLegendEntries(legendEntries, invalidLegendEntries) { const {inputs} = this.props inputs.entries.set(legendEntries) inputs.invalidEntries.set(invalidLegendEntries) } } const valuesToModel = ({entries}) => ({ entries: _.sortBy(entries, 'value') }) const additionalPolicy = () => ({ _: 'disallow' }) const LegendPanel = compose( _LegendPanel, recipeFormPanel({id: 'legend', fields, additionalPolicy, valuesToModel}) ) export const Legend = compose( _Legend, withRecipe(mapRecipeToProps) ) Legend.propTypes = { recipeId: PropTypes.string }
src/widgets/GalleryHub/SnippetGallery.js
mydearxym/mastani
/* * * SnippetGallery * */ import React from 'react' import T from 'prop-types' import { ICON } from '@/config' import { buildLog } from '@/utils/logger' import IconText from '@/widgets/IconText' import { Wrapper, Block, Header, IntroHead, LangPrefix, Title, Footer, } from './styles/snippet_gallery' /* eslint-disable-next-line */ const log = buildLog('c:SnippetGallery:index') const tmpItems = [ { id: '0', title: '客户端校验文件大小', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '1', title: '模式匹配', lang: 'ex', langColor: '#704A7C', icon: 'https://assets.coderplanets.com/icons/pl/elixir.png', }, { id: '2', title: 'clojure', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '3', title: 'Teambition', lang: 'ts', langColor: '#177488', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '4', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, { id: '5', title: 'whatever', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '6', title: 'Teambition', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/javascript.png', }, { id: '7', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, { id: '8', title: 'whatever', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/icons/pl/clojure.png', }, { id: '9', title: '少数派', lang: 'js', langColor: '#f4e069', icon: 'https://assets.coderplanets.com/editor/embeds/shaoshupai.png', }, ] const SnippetGallery = ({ items }) => { return ( <Wrapper> {items.map((item, index) => ( <Block key={item.id} borderTop={index <= 2} borderRight={(index + 1) % 3 !== 0} > <Header> <IntroHead> <LangPrefix color={item.langColor}>{item.lang}</LangPrefix> <Title>{item.title}</Title> </IntroHead> </Header> <div>---</div> <Footer> <IconText iconSrc={`${ICON}/shape/vote-up.svg`}>22</IconText> <IconText iconSrc={`${ICON}/shape/vote-up.svg`} size="tiny"> 类型转换 </IconText> </Footer> </Block> ))} </Wrapper> ) } SnippetGallery.propTypes = { items: T.arrayOf(T.object), } SnippetGallery.defaultProps = { items: tmpItems, } export default React.memo(SnippetGallery)
src/components/icons/MenuIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const MenuIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M0 0h24v24H0z" fill="none" /> <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" /> </svg> ); export default MenuIcon;
src/App.js
zero-coder/gamesfame
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1> GamesFame </h1> ); } }
src/title/TitlePlain.js
nashvail/zulip-mobile
import React from 'react'; import { StyleSheet, Text } from 'react-native'; import { CONTROL_SIZE } from '../styles'; const styles = StyleSheet.create({ title: { flex: 1, textAlign: 'center', fontSize: 16, paddingRight: CONTROL_SIZE, }, }); export default ({ text, color }) => <Text style={[styles.title, { color }]}>{text}</Text>;
packages/@lyra/components/src/lists/sortable/DragHandle.js
VegaPublish/vega-studio
// @flow import React from 'react' import DragBarsIcon from 'part:@lyra/base/bars-icon' import {createDragHandle} from '../sortable-factories' export default createDragHandle(props => ( <span className={props.className}> <DragBarsIcon /> </span> ))
example1/toilet/ios_views/setting/about.js
anchoretics/ztf-work-app
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, ScrollView } from 'react-native'; import Util from './../util'; class About extends Component{ render(){ return( <ScrollView style={styles.container}> <Text style={styles.text}>如果问题,请联系: [email protected]</Text> </ScrollView> ); } } const styles = StyleSheet.create({ container:{ flex: 1 }, text:{ fontSize:16, fontWeight:'300', marginBottom:15, marginLeft:10, marginTop:3 } }); module.exports = About;
app/imports/ui/containers/NewsRoomsList.js
mondrus/meteor-starter
/** * @Author: philip * @Date: 2017-05-27T20:46:16+00:00 * @Filename: NewsRoomsList.js * @Last modified by: philip * @Last modified time: 2017-05-29T13:40:09+00:00 */ import React from 'react'; import { composeWithTracker } from 'react-komposer'; import { Meteor } from 'meteor/meteor'; import NewsRooms from '/lib/collections/newsRooms'; import Loading from '../components/Loading.js'; import NewsRoomsList from '../components/NewsRoomsList.js'; const composer = (params, onData) => { const subscription = Meteor.subscribe('newsRooms.all'); if (subscription.ready()) { const newsRooms = NewsRooms.find().fetch(); onData(null, { newsRooms, params }); } }; export default composeWithTracker(composer, Loading)(NewsRoomsList);
src/svg-icons/communication/contact-mail.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationContactMail = (props) => ( <SvgIcon {...props}> <path d="M21 8V7l-3 2-3-2v1l3 2 3-2zm1-5H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2zM8 6c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H2v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1zm8-6h-8V6h8v6z"/> </SvgIcon> ); CommunicationContactMail = pure(CommunicationContactMail); CommunicationContactMail.displayName = 'CommunicationContactMail'; CommunicationContactMail.muiName = 'SvgIcon'; export default CommunicationContactMail;
src/routes/home/Home.js
joaquingatica/git-demo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Home.css'; class Home extends React.Component { static propTypes = { news: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string.isRequired, link: PropTypes.string.isRequired, content: PropTypes.string, })).isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>React.js News</h1> {this.props.news.map(item => ( <article key={item.link} className={s.newsItem}> <h1 className={s.newsTitle}><a href={item.link}>{item.title}</a></h1> <div className={s.newsDesc} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: item.content }} /> </article> ))} </div> </div> ); } } export default withStyles(s)(Home);
src/Router.js
sherlock221/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/svg-icons/av/music-video.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMusicVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/> </SvgIcon> ); AvMusicVideo = pure(AvMusicVideo); AvMusicVideo.displayName = 'AvMusicVideo'; export default AvMusicVideo;
src/hero/ReactTab.js
material-components/material-components-web-catalog
import {Component} from 'react'; import ReactTemplates from './CodeTemplates'; import equal from 'deep-equal'; import React from 'react'; import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'; import {prism} from 'react-syntax-highlighter/dist/esm/styles/prism'; import {CopyToClipboard} from 'react-copy-to-clipboard'; import {MDCRipple} from '@material/ripple/index'; import {gtagCopyCode} from '../constants'; import ReactGA from 'react-ga'; const customStyle = {background: 'transparent'}; export default class ReactTab extends Component { state = {codeString: ''}; ripples = []; initRipple = (el) => { if (el) { const ripple = MDCRipple.attachTo(el); ripple.unbounded = true; this.ripples.push(ripple); } }; initCodeString = () => { const {children, location} = this.props; const reactTemplateName = location.pathname.split('/component/')[1]; const val = ReactTemplates[reactTemplateName](children.props.config); const codeString = val ? val.replace(/\n\s*\n/g, '\n') : ''; this.setState({codeString}); }; componentDidMount() { this.initCodeString(); } componentDidUpdate(prevProps) { if (!equal(prevProps.config.options, this.props.config.options)) { this.initCodeString(); } } render() { return ( <React.Fragment> <SyntaxHighlighter lineProps={{style: {paddingBottom: 8}}} wrapLines showLineNumbers customStyle={customStyle} lineNumberStyle={{color: '#bab6b6'}} className='highlight-html' language='jsx' style={prism}>{this.state.codeString}</SyntaxHighlighter> <CopyToClipboard text={this.state.codeString} onCopy={() => { ReactGA.event({category: gtagCopyCode, action: 'react_code_copied', label: 'react_code_copied' }); this.setState({copied: true}) }}> <button className='mdc-icon-button material-icons copy-all-button' ref={this.initRipple}>file_copy</button> </CopyToClipboard> </React.Fragment> ); } }
src/js/components/input/grid_form/input_grid_form.js
rafaelfbs/realizejs
import React from 'react'; import _ from 'lodash'; import PropTypes from '../../../prop_types'; import { autobind, mixin } from '../../../utils/decorators'; import { uuid } from '../../../utils'; import GridForm from '../../grid_form/grid_form'; import InputGridFormFields from './input_grid_form_fields'; import InputHidden from '../input_hidden'; import InputBase from '../input_base'; import { CssClassMixin, } from '../../../mixins'; @mixin(CssClassMixin) export default class InputGridForm extends InputBase { static propTypes = { label: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]), fields: PropTypes.object, form: PropTypes.object, clientSide: PropTypes.bool, clientSideIdField: React.PropTypes.string, inputWrapperComponent: PropTypes.component, onSuccess: PropTypes.func, onDestroySuccess: PropTypes.func, }; static defaultProps = { themeClassKey: 'input.gridForm', className: '', fields: {}, form: {}, clientSide: true, clientSideIdField: '_clientSideId', inputWrapperComponent: null, onSuccess() {}, onDestroySuccess() {}, }; getDefaultFormProps() { return { formStyle: 'filter', inputWrapperComponent: this.props.inputWrapperComponent, }; } parseFormProp() { const formProp = _.merge(this.getDefaultFormProps(), this.props.form); formProp.inputs = Object.assign({}, this.props.inputs); return formProp; } parseColumnsProp() { const { columns } = this.props; return _.mapValues(columns, (column, key) => Object.assign(column, { name: column.name || key, })); } buildGridData() { const { value, clientSideIdField } = this.props; const dataRows = !value || value === '' ? [] : value.map((v) => { return { ...v, [clientSideIdField]: uuid.v4() }; }); return { dataRows }; } /* GridForm Result serializer */ serialize() { return { [this.props.name]: this.state.value }; } /* Event handling functions */ @autobind handleOnSuccess() { const gridFormValue = this.refs.gridForm.serialize(); this.setState({ value: gridFormValue }, () => ( this.props.onSuccess(gridFormValue) )); } @autobind handleOnDestroySuccess() { const gridFormValue = this.refs.gridForm.serialize(); this.setState({ value: gridFormValue }, () => ( this.props.onDestroySuccess(gridFormValue) )); } /* Renderers */ renderLabel() { const label = this.props.label; if (typeof label === 'boolean' && !label) { return []; } return ( <h5 className={this.themedClassName('input.gridForm.label')}> {label} </h5> ); } render() { return ( <div className={this.className()}> {this.renderLabel()} <GridForm {...this.propsWithoutCSS()} formComponent={InputGridFormFields} form={this.parseFormProp()} columns={this.parseColumnsProp()} data={this.buildGridData()} onSuccess={this.handleOnSuccess} onDestroySuccess={this.handleOnDestroySuccess} errors={this.props.errors} ref="gridForm" /> <InputHidden {...this.propsWithoutCSS()} value={this.serialize()} ref="input" /> </div> ); } }
src/modules/banner/BannerView.js
TheOne1006/TheOne1006-theone-io-app
/** * @flow */ import React, { Component } from 'react'; import { List } from 'immutable'; import Swiper from 'react-native-swiper'; import styles from './themes/light'; import Slide from './SlideView'; const imgList = [ 'https://res.cloudinary.com/theone/image/upload/v1430750900/o0ohnh0hb1t8dlc7o0ln.jpg', 'https://res.cloudinary.com/theone/image/upload/v1440311373/rxh0zcpxerpum2msj7hl.jpg', 'https://res.cloudinary.com/theone/image/upload/v1430750829/rjpkswtvxxte4105ttrg.jpg', ]; class Banner extends Component { state = { loadQueue: List([]), } componentWillMount() { this.setState({ loadQueue: List(new Array(imgList.length)), }); } loadHandle = (i: number) => { const { loadQueue } = this.state; const newLoadQueue = loadQueue.set(i, 1); this.setState({ loadQueue: newLoadQueue, }); } render() { const { loadQueue } = this.state; return ( <Swiper loadMinimal loadMinimalSize={1} height={240} style={styles.wrapper} > { imgList.map((item, i) => ( <Slide loadHandle={this.loadHandle} loaded={!!loadQueue.get(i)} uri={item} i={i} key={item} styles={styles} />), )} </Swiper> ); } } export default Banner;
src/svg-icons/notification/airline-seat-legroom-extra.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomExtra = (props) => ( <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/> </SvgIcon> ); NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra); NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra'; NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomExtra;
src/svg-icons/editor/format-indent-increase.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatIndentIncrease = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/> </SvgIcon> ); EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease); EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease'; EditorFormatIndentIncrease.muiName = 'SvgIcon'; export default EditorFormatIndentIncrease;
node_modules/react-bootstrap/es/SplitButton.js
NathanBWaters/jb_club
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 _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import Button from './Button'; import Dropdown from './Dropdown'; import SplitToggle from './SplitToggle'; import splitComponentProps from './utils/splitComponentProps'; var propTypes = _extends({}, Dropdown.propTypes, { // Toggle props. bsStyle: React.PropTypes.string, bsSize: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, /** * The content of the split button. */ title: React.PropTypes.node.isRequired, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: React.PropTypes.string, // Override generated docs from <Dropdown>. /** * @private */ children: React.PropTypes.node }); var SplitButton = function (_React$Component) { _inherits(SplitButton, _React$Component); function SplitButton() { _classCallCheck(this, SplitButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } SplitButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, toggleLabel = _props.toggleLabel, children = _props.children, props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']); var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent), dropdownProps = _splitComponentProps[0], buttonProps = _splitComponentProps[1]; return React.createElement( Dropdown, _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Button, _extends({}, buttonProps, { disabled: props.disabled, bsSize: bsSize, bsStyle: bsStyle }), title ), React.createElement(SplitToggle, { 'aria-label': toggleLabel || title, bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Dropdown.Menu, null, children ) ); }; return SplitButton; }(React.Component); SplitButton.propTypes = propTypes; SplitButton.Toggle = SplitToggle; export default SplitButton;
src/components/form/textarea.js
n7best/react-weui
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from '../../utils/classnames'; /** * weui wrapper for textarea * */ export default class TextArea extends Component { static propTypes = { /** * display word counter * */ showCounter: PropTypes.bool, /** * max character allow for textarea * */ maxLength: PropTypes.number, defaultValue: PropTypes.string, }; static defaultProps = { showCounter: true, defaultValue: undefined }; state = { textCounter: this.props.defaultValue ? this.props.defaultValue.length : 0 }; handleChange(e){ this.setState({textCounter: e.target.value.length}); //forward event to props if any if (this.props.onChange) this.props.onChange(e); } render(){ const { className, children, showCounter, maxLength, onChange, ...others } = this.props; const cls = classNames({ 'weui-textarea': true, [className]: className }); return ( <div> <textarea className={cls} maxLength={maxLength} onChange={this.handleChange.bind(this)} {...others}> {children} </textarea> { showCounter ? <div className="weui-textarea-counter"> <span>{this.state.textCounter}</span>{maxLength ? '/' + maxLength : false} </div> : false } </div> ); } };
docs/src/examples/modules/Dropdown/Types/DropdownExampleMultipleSelection.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const options = [ { key: 'angular', text: 'Angular', value: 'angular' }, { key: 'css', text: 'CSS', value: 'css' }, { key: 'design', text: 'Graphic Design', value: 'design' }, { key: 'ember', text: 'Ember', value: 'ember' }, { key: 'html', text: 'HTML', value: 'html' }, { key: 'ia', text: 'Information Architecture', value: 'ia' }, { key: 'javascript', text: 'Javascript', value: 'javascript' }, { key: 'mech', text: 'Mechanical Engineering', value: 'mech' }, { key: 'meteor', text: 'Meteor', value: 'meteor' }, { key: 'node', text: 'NodeJS', value: 'node' }, { key: 'plumbing', text: 'Plumbing', value: 'plumbing' }, { key: 'python', text: 'Python', value: 'python' }, { key: 'rails', text: 'Rails', value: 'rails' }, { key: 'react', text: 'React', value: 'react' }, { key: 'repair', text: 'Kitchen Repair', value: 'repair' }, { key: 'ruby', text: 'Ruby', value: 'ruby' }, { key: 'ui', text: 'UI Design', value: 'ui' }, { key: 'ux', text: 'User Experience', value: 'ux' }, ] const DropdownExampleMultipleSelection = () => ( <Dropdown placeholder='Skills' fluid multiple selection options={options} /> ) export default DropdownExampleMultipleSelection
react-flux-mui/js/material-ui/src/svg-icons/av/replay-30.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay30 = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-2.4 8.5h.4c.2 0 .4-.1.5-.2s.2-.2.2-.4v-.2s-.1-.1-.1-.2-.1-.1-.2-.1h-.5s-.1.1-.2.1-.1.1-.1.2v.2h-1c0-.2 0-.3.1-.5s.2-.3.3-.4.3-.2.4-.2.4-.1.5-.1c.2 0 .4 0 .6.1s.3.1.5.2.2.2.3.4.1.3.1.5v.3s-.1.2-.1.3-.1.2-.2.2-.2.1-.3.2c.2.1.4.2.5.4s.2.4.2.6c0 .2 0 .4-.1.5s-.2.3-.3.4-.3.2-.5.2-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.4-.1-.6h.8v.2s.1.1.1.2.1.1.2.1h.5s.1-.1.2-.1.1-.1.1-.2v-.5s-.1-.1-.1-.2-.1-.1-.2-.1h-.6v-.7zm5.7.7c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5c0-.1-.1-.2-.1-.3s-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvReplay30 = pure(AvReplay30); AvReplay30.displayName = 'AvReplay30'; AvReplay30.muiName = 'SvgIcon'; export default AvReplay30;
packages/components/src/SubHeaderBar/SubHeader.stories.js
Talend/ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import FilterBar from '../FilterBar'; import Tag from '../Tag'; import SubHeaderBar from './SubHeaderBar.component'; const viewProps = { title: 'My Long Title is Long Long Lé Long La La La Lé Long Long Long Long', onEdit: action('onEdit'), onSubmit: action('onSubmit'), onCancel: action('onCancel'), onChange: action('onChange'), }; const backAction = action('onGoBack'); const injectedComponentsRight = [ { label: 'icon + text', bsStyle: 'link', icon: 'talend-share-alt', onClick: action('icon + text'), }, { label: 'action1', bsStyle: 'link', icon: 'talend-share-alt', onClick: action('return action1'), hideLabel: true, }, { label: 'Action2', bsStyle: 'link', icon: 'talend-activity', onClick: action('return action2'), displayMode: 'iconToggle', active: true, }, { label: 'action3', bsStyle: 'link', icon: 'talend-bell', onClick: action('return action3'), hideLabel: true, displayMode: 'iconToggle', }, ]; const componentAction = { label: 'action4', bsStyle: 'link', icon: 'talend-bell', onClick: action('return action4'), hideLabel: true, }; const center = ( <SubHeaderBar.Content center> <FilterBar t={() => action('t')} onFilter={() => action('onFilter')} navbar docked={false} dockable={false} /> </SubHeaderBar.Content> ); export default { title: 'Navigation/SubHeader', }; export const WithDefault = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} /> </div> ); export const WithEditable = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} editable /> </div> ); export const WithIcon = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" onGoBack={backAction} /> </div> ); export const WithSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitle="mySubTitle" onGoBack={backAction} /> </div> ); export const WithLoadingSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitleLoading onGoBack={backAction} /> </div> ); export const WithCustomSubtitle = () => ( <div> <SubHeaderBar {...viewProps} subTitle="mySubTitle" onGoBack={backAction} subTitleAs={({ subTitle }) => <Tag bsStyle="info">{subTitle}</Tag>} /> </div> ); export const WithRightComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} right={injectedComponentsRight} /> </div> ); export const WithCenterComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} center={[componentAction]}> {center} </SubHeaderBar> </div> ); export const WithCenterComponentsWithTagProps = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction}> <SubHeaderBar.Content tag="form" center> <input id="inputTitle" type="text" onChange={action('onChange')} value="" /> </SubHeaderBar.Content> </SubHeaderBar> </div> ); export const WithCenterRightComponents = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} right={injectedComponentsRight}> {center} </SubHeaderBar> </div> ); export const WithAll = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} right={injectedComponentsRight} > {center} </SubHeaderBar> </div> ); export const WithSkeleton = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} loading > {center} </SubHeaderBar> </div> ); export const WithInProgress = () => ( <div> <SubHeaderBar {...viewProps} iconId="talend-file-csv-o" subTitle="mySubTitle" onGoBack={backAction} inProgress editable > {center} </SubHeaderBar> </div> ); export const WithRightActionsLoading = () => ( <div> <SubHeaderBar {...viewProps} onGoBack={backAction} rightActionsLoading /> </div> );
app/containers/Home/subPage/List.js
owen1190/ele-react
import React from 'react' import PureRenderMixin from 'react-addons-pure-render-mixin' import {get} from '../../../fetch/get'; import { homeListData } from '../../../../mock/getData' import ListCompoent from '../../../components/ListComponent' import LoadMore from '../../../components/LoadMore' import {Link} from 'react-router'; import './style.less' class List extends React.Component{ constructor(props) { super(props); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); this.state = { data: [], hasMore: false, isLoadingMore: false, page: 0 } } render(){ return ( <div> <h2 className="home-list-title">推荐商家</h2> { this.state.data.length ? <ListCompoent data={this.state.data}/> : <div>{/* 加载中... */}</div> } { this.state.hasMore ? <LoadMore isLoadingMore={this.state.isLoadingMore} loadMoreFn={this.loadMoreData.bind(this)}/> : '' } </div> ) } componentDidMount(){ this.resultHandle(homeListData()) } resultHandle(result){ result.then(res =>{ this.setState({ data: res, hasMore:true, }) }) } loadMoreData(){ this.setState({ isLoadingMore:true }) const page = this.state.page; this.resultHandle(homeListData()) this.setState({ page:page+1 }) } } export default List
src/components/social-link.js
MozillaIndia/mozillaindia.github.io
import React from 'react' import { FaTwitterSquare, FaFacebookSquare, FaInstagram, FaMeetup, FaTelegramPlane, FaGithub, FaGlobe, } from 'react-icons/fa' const getIconByType = ({ type }) => { switch (type) { case 'website': return <FaGlobe size="25" color="#0088cc" /> case 'telegram': return <FaTelegramPlane size="25" color="#0088cc" /> case 'twitter': return <FaTwitterSquare size="25" color="#1da1f2" /> case 'github': return <FaGithub size="25" color="#000" /> case 'instagram': return <FaInstagram size="25" color="#000" /> case 'facebook': return <FaFacebookSquare size="25" color="#1da1f2" /> case 'meetup': return <FaMeetup size="25" color="#1da1f2" /> default: return <FaGlobe /> } } const SocialLink = ({ type, link }) => ( <a href={link}> <span className="icon-tile">{getIconByType({ type })}</span> </a> ) export default SocialLink
src/components/placeholder.js
samuelneff/react-play
import React from 'react'; class Placeholder extends React.Component { render() { return ( <div> <p>This is a starting point for a project that uses:</p> <ul> <li><a href="https://github.com/lukehoban/es6features">ES6 (aka EcmaScript 2015)</a></li> <li><a href="https://facebook.github.io/react/">React</a></li> <li><a href="https://babeljs.io/">Babel</a></li> <li><a href="http://browserify.org/">Browserify</a></li> <li><a href="https://github.com/babel/babelify">Babelify</a></li> <li><a href="http://gulpjs.com/">Gulp</a></li> <li><a href="https://nodejs.org/">Node</a></li> <li><a href="http://expressjs.com/">Express</a></li> </ul> <p> See the GitHub repository at: <a href="https://github.com/poshaughnessy/es6-react-babel-starter-template">github.com/poshaughnessy/es6-react-babel-starter-template</a> </p> <p>Feel free to fork, copy or use however you like.</p> <p> Also please get in touch via <a href="mailto:[email protected]">email</a> or <a href="http://twitter.com/poshaughnessy">Twitter</a> if you have any comments/suggestions/questions. </p> <p><em>Peter O'Shaughnessy</em></p> </div> ); } } export default Placeholder;
source/Plx.js
Stanko/react-plx
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import BezierEasing from 'bezier-easing'; import ScrollManager from 'window-scroll-manager'; // Check if code is running in the browser (important for universal rendering) const WINDOW_EXISTS = typeof window !== 'undefined'; // Regex that checks for numbers in string // formatted as "{number}{unit}" where unit is "px", "vh", "%" or none const START_END_DURATION_REGEX = /^-?\d+(\.\d+)?(px|vh|%)?$/; const DEFAULT_UNIT = 'px'; const DEFAULT_ANGLE_UNIT = 'deg'; const ANGLE_PROPERTIES = [ 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY', 'skewZ', 'hueRotate', ]; const EASINGS = { ease: [0.25, 0.1, 0.25, 1.0], easeIn: [0.42, 0.0, 1.00, 1.0], easeOut: [0.00, 0.0, 0.58, 1.0], easeInOut: [0.42, 0.0, 0.58, 1.0], easeInSine: [0.47, 0, 0.745, 0.715], easeOutSine: [0.39, 0.575, 0.565, 1], easeInOutSine: [0.445, 0.05, 0.55, 0.95], easeInQuad: [0.55, 0.085, 0.68, 0.53], easeOutQuad: [0.25, 0.46, 0.45, 0.94], easeInOutQuad: [0.455, 0.03, 0.515, 0.955], easeInCubic: [0.55, 0.055, 0.675, 0.19], easeOutCubic: [0.215, 0.61, 0.355, 1], easeInOutCubic: [0.645, 0.045, 0.355, 1], easeInQuart: [0.895, 0.03, 0.685, 0.22], easeOutQuart: [0.165, 0.84, 0.44, 1], easeInOutQuart: [0.77, 0, 0.175, 1], easeInQuint: [0.755, 0.05, 0.855, 0.06], easeOutQuint: [0.23, 1, 0.32, 1], easeInOutQuint: [0.86, 0, 0.07, 1], easeInExpo: [0.95, 0.05, 0.795, 0.035], easeOutExpo: [0.19, 1, 0.22, 1], easeInOutExpo: [1, 0, 0, 1], easeInCirc: [0.6, 0.04, 0.98, 0.335], easeOutCirc: [0.075, 0.82, 0.165, 1], easeInOutCirc: [0.785, 0.135, 0.15, 0.86], }; // Color regexes // 0 - 199 | 200 - 249 | 250 - 255 const REGEX_0_255 = '(1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'; // 0.0 - 1.9999... const REGEX_0_1 = '([01](\\.\\d+)?)'; // 00 - FF const REGEX_TWO_HEX_DIGITS = '([a-f\\d]{2})'; const HEX_REGEX = new RegExp(`^#${ REGEX_TWO_HEX_DIGITS }${ REGEX_TWO_HEX_DIGITS }${ REGEX_TWO_HEX_DIGITS }$`, 'i'); const RGB_REGEX = new RegExp(`^rgb\\(${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_255 }\\)$`, 'i'); const RGBA_REGEX = new RegExp(`^rgba\\(${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_255 },${ REGEX_0_1 }\\)$`, 'i'); const SCROLL_OFFSET = 50; const RESIZE_DEBOUNCE_TIMEOUT = 150; // CSS transform map const TRANSFORM_MAP = { rotate: (value, unit = DEFAULT_ANGLE_UNIT) => `rotate(${ value }${ unit })`, rotateX: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateX(${ value }${ unit })`, rotateY: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateY(${ value }${ unit })`, rotateZ: (value, unit = DEFAULT_ANGLE_UNIT) => `rotateZ(${ value }${ unit })`, scale: value => `scale(${ value })`, scaleX: value => `scaleX(${ value })`, scaleY: value => `scaleY(${ value })`, scaleZ: value => `scaleZ(${ value })`, skew: (value, unit = DEFAULT_UNIT) => `skew(${ value }${ unit })`, skewX: (value, unit = DEFAULT_UNIT) => `skewX(${ value }${ unit })`, skewY: (value, unit = DEFAULT_UNIT) => `skewY(${ value }${ unit })`, skewZ: (value, unit = DEFAULT_UNIT) => `skewZ(${ value }${ unit })`, translateX: (value, unit = DEFAULT_UNIT) => `translateX(${ value }${ unit })`, translateY: (value, unit = DEFAULT_UNIT) => `translateY(${ value }${ unit })`, translateZ: (value, unit = DEFAULT_UNIT) => `translateZ(${ value }${ unit })`, }; // Order of CSS transforms matters const ORDER_OF_TRANSFORMS = [ 'translateX', 'translateY', 'translateZ', 'skew', 'skewX', 'skewY', 'skewZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', ]; // CSS properties that use color values const COLOR_PROPERTIES = [ 'backgroundColor', 'borderBottomColor', 'borderColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'fill', 'stroke', ]; // CSS filter map // blur() // brightness() // contrast() // grayscale() // hue-rotate() // invert() // opacity() // use opacityFilter // saturate() // sepia() // Not supported // drop-shadow() // url() const FILTER_MAP = { blur: (value, unit = DEFAULT_UNIT) => `blur(${ value }${ unit })`, brightness: value => `brightness(${ value })`, contrast: value => `contrast(${ value })`, grayscale: value => `grayscale(${ value })`, hueRotate: (value, unit = DEFAULT_ANGLE_UNIT) => `hue-rotate(${ value }${ unit })`, invert: value => `invert(${ value })`, opacityFilter: value => `opacity(${ value })`, saturate: value => `saturate(${ value })`, sepia: value => `sepia(${ value })`, }; const FILTER_PROPERTIES = [ 'blur', 'brightness', 'contrast', 'grayscale', 'hueRotate', 'invert', 'opacityFilter', 'saturate', 'sepia', ]; // Props to be removed from passing directly to the component element const PROPS_TO_OMIT = [ 'animateWhenNotInViewport', 'children', 'className', 'freeze', 'parallaxData', 'style', 'tagName', 'onPlxStart', 'onPlxEnd', ]; // Get element's top offset function getElementTop(el) { let top = 0; let element = el; do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); return top; } // Returns CSS unit function getUnit(property, unit) { let propertyUnit = unit || DEFAULT_UNIT; if (ANGLE_PROPERTIES.indexOf(property) >= 0) { propertyUnit = unit || DEFAULT_ANGLE_UNIT; } return propertyUnit; } // Takes string value (in px/vh/%) and returns number function getValueInPx(value, maxScroll) { const floatValue = parseFloat(value); const unit = value.match(START_END_DURATION_REGEX)[2] || null; const vh = window.innerHeight / 100; let valueInPx = value; switch (unit) { case 'vh': valueInPx = vh * floatValue; break; case '%': valueInPx = maxScroll * floatValue / 100; break; default: valueInPx = floatValue; } return valueInPx; } // Takes start/end/duration props // and return number (in pixels) based on prop type (number, string, dom element) function convertPropToPixels(propName, propValue, maxScroll, offset = 0) { let propValueInPx = propValue; const isElement = propValue instanceof HTMLElement; const keyCodes = { ZERO: 48, NINE: 57, }; if (typeof propValue === 'number') { propValueInPx = propValue; } else if (START_END_DURATION_REGEX.test(propValue)) { propValueInPx = getValueInPx(propValue, maxScroll); } else if ( isElement || typeof propValue === 'string' && (propValue.charCodeAt(0) < keyCodes.ZERO || propValue.charCodeAt(0) > keyCodes.NINE) ) { const element = isElement ? propValue : document.querySelector(propValue); if (!element) { console.warn(`Plx, ERROR: ${ propName } selector matches no elements: "${ propValue }"`); // eslint-disable-line return null; } if (propName === 'start' || propName === 'end') { // START or END // Element enters the viewport propValueInPx = getElementTop(element) - window.innerHeight; } else if (propName === 'duration') { // DURATION // Height of the element propValueInPx = element.offsetHeight; } } else { console.warn(`Plx, ERROR: "${ propValue }" is not a valid ${ propName } value, check documenation`); // eslint-disable-line return null; } // Transform offset to px let offsetInPx = 0; if (typeof offset === 'number') { offsetInPx = offset; } else if (START_END_DURATION_REGEX.test(offset)) { offsetInPx = getValueInPx(offset, maxScroll); } // Add offset propValueInPx += offsetInPx; if (propValueInPx < 0) { propValueInPx = 0; } return propValueInPx; } // Convers color in hex format into object { r, g, b, a } function hexToObject(hex) { // Convert #abc to #aabbcc const color = hex.length === 4 ? `#${ hex[1] }${ hex[1] }${ hex[2] }${ hex[2] }${ hex[3] }${ hex[3] }` : hex; const result = HEX_REGEX.exec(color); // Safety check, if color is in the wrong format if (!result) { console.warn(`Plx, ERROR: hex color is not in the right format: "${ hex }"`); // eslint-disable-line no-console return null; } // All color functions are returning { r, g, b, a } object return { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), a: 1, }; } // Convers color in rgb format into object { r, g, b, a } function rgbToObject(rgb) { const isRgba = rgb.toLowerCase().indexOf('rgba') === 0; const color = rgb.replace(/ /g, ''); const result = isRgba ? RGBA_REGEX.exec(color) : RGB_REGEX.exec(color); // Safety check, if color is in the wrong format if (!result) { console.warn(`Plx, ERROR: rgb or rgba color is not in the right format: "${ rgb }"`); // eslint-disable-line return null; } // All color functions are returning { r, g, b, a } object return { r: parseInt(result[1], 10), g: parseInt(result[2], 10), b: parseInt(result[3], 10), a: isRgba ? parseFloat(result[4]) : 1, }; } // Calculates the current value for parallaxing property function parallax(scrollPosition, start, duration, startValue, endValue, easing) { let min = startValue; let max = endValue; const invert = startValue > endValue; // Safety check, if "startValue" is in the wrong format if (typeof startValue !== 'number') { console.warn(`Plx, ERROR: startValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "endValue" is in the wrong format if (typeof endValue !== 'number') { console.warn(`Plx, ERROR: endValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "duration" is in the wrong format if (typeof duration !== 'number' || duration === 0) { console.warn(`Plx, ERROR: duration is zero or not a number (type: "${ typeof duration }", value: "${ duration }")`); // eslint-disable-line return null; } if (invert) { min = endValue; max = startValue; } let percentage = ((scrollPosition - start) / duration); if (percentage > 1) { percentage = 1; } else if (percentage < 0) { percentage = 0; } // Apply easing if (easing) { const easingPropType = typeof easing; if (easingPropType === 'object' && easing.length === 4) { percentage = BezierEasing( easing[0], easing[1], easing[2], easing[3] )(percentage); } else if (easingPropType === 'string' && EASINGS[easing]) { percentage = BezierEasing( EASINGS[easing][0], EASINGS[easing][1], EASINGS[easing][2], EASINGS[easing][3] )(percentage); } else if (easingPropType === 'function') { percentage = easing(percentage); } } let value = percentage * (max - min); if (invert) { value = max - value; } else { value += min; } // Rounding to 4 decimals (.toFixed(4) returns a string) return Math.floor(value * 10000) / 10000; } // Calculates current value for color parallax function colorParallax(scrollPosition, start, duration, startValue, endValue, easing) { let startObject = null; let endObject = null; if (startValue[0].toLowerCase() === 'r') { startObject = rgbToObject(startValue); } else { startObject = hexToObject(startValue); } if (endValue[0].toLowerCase() === 'r') { endObject = rgbToObject(endValue); } else { endObject = hexToObject(endValue); } if (startObject && endObject) { const r = parallax(scrollPosition, start, duration, startObject.r, endObject.r, easing); const g = parallax(scrollPosition, start, duration, startObject.g, endObject.g, easing); const b = parallax(scrollPosition, start, duration, startObject.b, endObject.b, easing); const a = parallax(scrollPosition, start, duration, startObject.a, endObject.a, easing); return `rgba(${ parseInt(r, 10) }, ${ parseInt(g, 10) }, ${ parseInt(b, 10) }, ${ a })`; } return null; } // Applies property parallax to the style object function applyProperty(scrollPosition, propertyData, startPosition, duration, style, easing) { const { startValue, endValue, property, unit, } = propertyData; // If property is one of the color properties // Use it's parallax method const isColor = COLOR_PROPERTIES.indexOf(property) > -1; const parallaxMethod = isColor ? colorParallax : parallax; // Get new CSS value const value = parallaxMethod( scrollPosition, startPosition, duration, startValue, endValue, easing ); // Get transform function const transformMethod = TRANSFORM_MAP[property]; const filterMethod = FILTER_MAP[property]; const newStyle = style; if (transformMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Transforms, apply value to transform function newStyle.transform[property] = transformMethod(value, propertyUnit); if (!newStyle.willChange.includes('transform')) { newStyle.willChange.push('transform'); } } else if (filterMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Filters, apply value to filter function newStyle.filter[property] = filterMethod(value, propertyUnit); if (!newStyle.willChange.includes('filter')) { newStyle.willChange.push('filter'); } } else { // All other properties newStyle[property] = value; if (!newStyle.willChange.includes(property)) { newStyle.willChange.push(property); } // Add unit if it is passed if (unit) { newStyle[property] += unit; } } return newStyle; } // Returns CSS classes based on animation state function getClasses(lastSegmentScrolledBy, isInSegment, parallaxData) { let cssClasses = null; if (lastSegmentScrolledBy === null) { cssClasses = 'Plx--above'; } else if (lastSegmentScrolledBy === parallaxData.length - 1 && !isInSegment) { cssClasses = 'Plx--below'; } else if (lastSegmentScrolledBy !== null && isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; cssClasses = `Plx--active Plx--in Plx--in-${ segmentName }`; } else if (lastSegmentScrolledBy !== null && !isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; const nextSegmentName = parallaxData[lastSegmentScrolledBy + 1].name || lastSegmentScrolledBy + 1; cssClasses = `Plx--active Plx--between Plx--between-${ segmentName }-and-${ nextSegmentName }`; } return cssClasses; } // Checks if class contains 'active' function checkIfActive(classes) { return classes.indexOf('Plx--active') > -1; } // Omits "keysToOmit" from "object" function omit(object, keysToOmit) { const result = {}; Object.keys(object).forEach(key => { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } }); return result; } // Main update function // Returns new state object based on props and scroll position function getNewState(scrollPosition, props, state, element) { const { animateWhenNotInViewport, disabled, freeze, parallaxData, } = props; const { showElement, plxStyle, plxStateClasses, } = state; // Do nothing if animation is disabled, frozen // or if element is not rendered yet if ((freeze && showElement) || !element || disabled) { return null; } // Check if element is in viewport // Small offset is added to prevent page jumping if (!animateWhenNotInViewport) { const rect = element.getBoundingClientRect(); const isTopAboveBottomEdge = rect.top < window.innerHeight + SCROLL_OFFSET; const isBottomBelowTopEdge = rect.top + rect.height > -SCROLL_OFFSET; if (!isTopAboveBottomEdge || !isBottomBelowTopEdge) { return null; } } const newState = {}; // Style to be applied to our element let newStyle = { willChange: [], transform: {}, filter: {}, }; // This means "componentDidMount" did happen and that we should show our element if (!showElement) { newState.showElement = true; } const appliedProperties = []; const segments = []; let isInSegment = false; let lastSegmentScrolledBy = null; const bodyHeight = document.documentElement.scrollHeight || document.body.scrollHeight; const maxScroll = bodyHeight - window.innerHeight; for (let i = 0; i < parallaxData.length; i++) { const { duration, easing, endOffset, properties, startOffset, } = parallaxData[i]; const start = parallaxData[i].start === 'self' ? element : parallaxData[i].start; const end = parallaxData[i].end === 'self' ? element : parallaxData[i].end; const startInPx = convertPropToPixels('start', start, maxScroll, startOffset); let durationInPx = null; let endInPx = null; // End has higher priority than duration if (typeof end !== 'undefined') { endInPx = convertPropToPixels('end', end, maxScroll, endOffset); durationInPx = endInPx - startInPx; } else { durationInPx = convertPropToPixels('duration', duration, maxScroll); endInPx = startInPx + durationInPx; } // If segment is below scroll position skip it if (scrollPosition < startInPx) { break; } const isScrolledByStart = scrollPosition >= startInPx; if (isScrolledByStart) { lastSegmentScrolledBy = i; } // If active segment exists, apply his properties if (scrollPosition >= startInPx && scrollPosition <= endInPx) { isInSegment = true; properties.forEach(propertyData => { // eslint-disable-line no-loop-func const { property } = propertyData; // Save which properties are applied to the active segment // So they are not re-applied for other segments appliedProperties.push(property); // Apply property style newStyle = applyProperty( scrollPosition, propertyData, startInPx, durationInPx, newStyle, easing ); }); } else { // Push non active segments above the scroll position to separate array // This way "durationInPx" and "startInPx" are not calculated again // and segments below scroll position are skipped in the next step segments.push({ easing, durationInPx, properties, startInPx, }); } } // These are only segments that are completly above scroll position segments.forEach(data => { const { easing, durationInPx, properties, startInPx, } = data; properties.forEach((propertyData) => { const { property } = propertyData; // Skip propery that was changed for active segment if (appliedProperties.indexOf(property) > -1) { return; } // These styles that are the ones changed by segments // that are above active segment newStyle = applyProperty( scrollPosition, propertyData, startInPx, durationInPx, newStyle, easing ); }); }); // Sort transforms by ORDER_OF_TRANSFORMS // as order of CSS transforms matters const transformsOrdered = []; ORDER_OF_TRANSFORMS.forEach(transformKey => { if (newStyle.transform[transformKey]) { transformsOrdered.push(newStyle.transform[transformKey]); } }); // Concat transforms and add webkit prefix newStyle.transform = transformsOrdered.join(' '); newStyle.WebkitTransform = newStyle.transform; const filtersArray = []; FILTER_PROPERTIES.forEach(filterKey => { if (newStyle.filter[filterKey]) { filtersArray.push(newStyle.filter[filterKey]); } }); // Concat filters and add webkit prefix newStyle.filter = filtersArray.join(' '); newStyle.WebkitFilter = newStyle.filter; // "Stupid" check if style should be updated if (JSON.stringify(plxStyle) !== JSON.stringify(newStyle)) { newState.plxStyle = newStyle; } // Adding state class const newPlxStateClasses = getClasses(lastSegmentScrolledBy, isInSegment, parallaxData); if (newPlxStateClasses !== plxStateClasses) { newState.plxStateClasses = newPlxStateClasses; } if (Object.keys(newState).length) { return newState; } return null; } export default class Plx extends Component { constructor(props) { super(); // Binding handlers this.handleScrollChange = this.handleScrollChange.bind(this); this.handleResize = this.handleResize.bind(this); this.state = { element: null, showElement: false, plxStateClasses: '', plxStyle: {}, }; // Skipping type checking as PropTypes will give a warning if the props aren't functions this.plxStartEnabled = props.onPlxStart !== null; this.plxEndEnabled = props.onPlxEnd !== null; } componentDidMount() { // Get scroll manager singleton this.scrollManager = new ScrollManager(); // Add listeners window.addEventListener('window-scroll', this.handleScrollChange); window.addEventListener('resize', this.handleResize); this.update(); } componentDidUpdate(prevProps, prevState) { const wasActive = checkIfActive(prevState.plxStateClasses); const isActive = checkIfActive(this.state.plxStateClasses); // Update only if props changed if (prevProps !== this.props) { this.update(); } // Callbacks if ((this.plxStartEnabled || this.plxEndEnabled) && prevState.plxStateClasses !== this.state.plxStateClasses) { if (this.plxStartEnabled && !wasActive && isActive) { this.props.onPlxStart(); } else if (this.plxEndEnabled && wasActive && !isActive) { this.props.onPlxEnd(); } } } componentWillUnmount() { window.removeEventListener('window-scroll', this.handleScrollChange); window.removeEventListener('resize', this.handleResize); clearTimeout(this.resizeDebounceTimeoutID); this.resizeDebounceTimeoutID = null; if (this.scrollManager) { this.scrollManager.removeListener(); } } update(scrollPosition = null) { const currentScrollPosition = scrollPosition === null ? this.scrollManager.getScrollPosition().scrollPositionY : scrollPosition; const newState = getNewState( currentScrollPosition, this.props, this.state, this.element ); if (newState) { this.setState(newState); } } handleResize() { clearTimeout(this.resizeDebounceTimeoutID); this.resizeDebounceTimeoutID = setTimeout(() => { this.update(); }, RESIZE_DEBOUNCE_TIMEOUT); } handleScrollChange(e) { this.update(e.detail.scrollPositionY); } render() { const { children, className, disabled, style, tagName, } = this.props; const { showElement, plxStyle, plxStateClasses, } = this.state; const Tag = tagName; let elementStyle = style; if (!disabled) { elementStyle = { ...style, ...plxStyle, // Hide element before until it is rendered // This prevents jumps if page is scrolled and then refreshed visibility: showElement ? null : 'hidden', }; } return ( <Tag { ...omit(this.props, PROPS_TO_OMIT) } className={ `Plx ${ plxStateClasses } ${ className }` } style={ elementStyle } ref={ el => this.element = el } > { children } </Tag> ); } } const propertiesItemType = PropTypes.shape({ startValue: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, endValue: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]).isRequired, property: PropTypes.string.isRequired, unit: PropTypes.string, }); // Check for the universal rendering // HTMLElement in the proptypes breaks on server // https://github.com/Stanko/react-plx/issues/25 const SafeHTMLElement = WINDOW_EXISTS ? window.HTMLElement : {}; const parallaxDataType = PropTypes.shape({ start: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]).isRequired, startOffset: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]), duration: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]), end: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(SafeHTMLElement), ]), endOffset: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]), properties: PropTypes.arrayOf(propertiesItemType).isRequired, easing: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, PropTypes.func, ]), name: PropTypes.string, }); Plx.propTypes = { animateWhenNotInViewport: PropTypes.bool, children: PropTypes.any, className: PropTypes.string, disabled: PropTypes.bool, freeze: PropTypes.bool, parallaxData: PropTypes.arrayOf(parallaxDataType), style: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object])), tagName: PropTypes.string, onPlxStart: PropTypes.func, onPlxEnd: PropTypes.func, }; Plx.defaultProps = { animateWhenNotInViewport: false, children: null, className: '', disabled: false, freeze: false, parallaxData: [], style: {}, tagName: 'div', onPlxStart: null, onPlxEnd: null, };
node_modules/react-bootstrap/es/InputGroupButton.js
CallumRocks/ReduxSimpleStarter
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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var InputGroupButton = function (_React$Component) { _inherits(InputGroupButton, _React$Component); function InputGroupButton() { _classCallCheck(this, InputGroupButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } InputGroupButton.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return InputGroupButton; }(React.Component); export default bsClass('input-group-btn', InputGroupButton);
app/templates/src/components/Version/Version.js
KarolAltamirano/generator-react-web
// @flow /* eslint-disable no-console */ import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import styles from './styles.scss'; import config from '../../../config.json'; export default class Version extends Component { state: Object = { version: config.build.version, time: config.build.time, }; componentDidMount() { console.log( `\n%cv${this.state.version}%c %c${this.state.time}%c\n\n`, 'color: #ffffff; background: #00aa00; padding: 1px 5px;', 'color: #ffffff; background: #d1eeee; padding: 1px 5px;', 'color: #ffffff; background: #00aa00; padding: 1px 5px;', 'background: #ffffff;' ); } render(): ?React$Element<any> { return ( <div className={styles.wrapper}> <FormattedMessage {...messages.version} values={{ version: this.state.version, time: this.state.time }} /> </div> ); } }
src/routes/Pianoroll/components/Pianoroll.js
rkram5424/BentoBeats
import React from 'react' export const HomeView = () => ( <div> <h4>Pianoroll!</h4> </div> ) export default HomeView
internals/templates/app.js
williamsnieves/reactnews
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/routes/home/index.js
tlin108/chaf
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,content}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Layout><Home news={data.news} /></Layout>, }; }, };
frontend/src/common/components/text-item.js
OptimusCrime/youkok2
import React from 'react'; export const TextItem = ({ text }) => ( <li className="list-group-item"> {text} </li> );
BookSearch/index.ios.js
onezens/react-native-repo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import Featured from ('./Featured.js'); import Search from ('./Search.js'); export default class BookSearch extends Component { constructor(props) { super(props); this.state = { selectedTab: 'featured' }; } render() { return ( <TabBarIOS selectedTab={this.state.selectedTab}> <TabBarIOS.Item selected={this.state.selectedTab === 'featured'} icon={{uri:'featured'}} onPress={() => { this.setState({ selectedTab: 'featured' }); }}> <Featured/> </TabBarIOS.Item> <TabBarIOS.Item selected={this.state.selectedTab === 'search'} icon={{uri:'search'}} onPress={() => { this.setState({ selectedTab: 'search' }); }}> <Search/> </TabBarIOS.Item> </TabBarIOS> ); } } // const styles = StyleSheet.create({ // container: { // flex: 1, // justifyContent: 'center', // alignItems: 'center', // backgroundColor: '#F5FCFF', // }, // welcome: { // fontSize: 20, // textAlign: 'center', // margin: 10, // }, // instructions: { // textAlign: 'center', // color: '#333333', // marginBottom: 5, // }, // }); AppRegistry.registerComponent('BookSearch', () => BookSearch);
react/features/base/react/components/web/BaseIndicator.js
jitsi/jitsi-meet
/* @flow */ import { makeStyles } from '@material-ui/core'; import React from 'react'; import { translate } from '../../../i18n'; import { Icon } from '../../../icons'; import { Tooltip } from '../../../tooltip'; /** * The type of the React {@code Component} props of {@link BaseIndicator}. */ type Props = { /** * Additional CSS class name. */ className: string, /** * The icon component to use. */ icon: Object, /** * The CSS classnames to set on the icon element of the component. */ iconClassName: string, /** * The color of the icon. */ iconColor: ?string, /** * Id of the icon to be rendered. */ iconId?: string, /** * The font size for the icon. */ iconSize: string, /** * The ID attribute to set on the root element of the component. */ id: string, /** * Invoked to obtain translated strings. */ t: Function, /** * The translation key to use for displaying a tooltip when hovering over * the component. */ tooltipKey: string, /** * From which side of the indicator the tooltip should appear from, * defaulting to "top". */ tooltipPosition: string }; const useStyles = makeStyles(() => { return { indicator: { width: '20px', height: '20px', display: 'flex', alignItems: 'center', justifyContent: 'center' } }; }); /** * React {@code Component} for showing an icon with a tooltip. * * @returns {ReactElement} */ const BaseIndicator = ({ className = '', icon, iconClassName, iconColor, iconId, iconSize, id = '', t, tooltipKey, tooltipPosition = 'top' }: Props) => { const styles = useStyles(); const style = {}; if (iconSize) { style.fontSize = iconSize; } return ( <div className = { styles.indicator }> <Tooltip content = { t(tooltipKey) } position = { tooltipPosition }> <span className = { className } id = { id }> <Icon className = { iconClassName } color = { iconColor } id = { iconId } src = { icon } style = { style } /> </span> </Tooltip> </div> ); }; export default translate(BaseIndicator);
app/javascript/mastodon/features/notifications/components/clear_column_button.js
kazh98/social.arnip.org
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; export default class ClearColumnButton extends React.PureComponent { static propTypes = { onClick: PropTypes.func.isRequired, }; render () { return ( <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button> ); } }
src/Interpolate.js
Azerothian/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; import assign from './utils/Object.assign'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { format: React.PropTypes.string }, getDefaultProps() { return { component: 'span' }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = assign({}, this.props); delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
src/client.js
oxoooo/webpack-babel-react-startup
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './configureStore'; import App from './components/App'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
src/routes/content/index.js
mauphes/own-git-project
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Content from './Content'; import fetch from '../../core/fetch'; export default { path: '*', async action({ path }) { // eslint-disable-line react/prop-types const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: `{content(path:"${path}"){path,title,content,component}}`, }), credentials: 'include', }); if (resp.status !== 200) throw new Error(resp.statusText); const { data } = await resp.json(); if (!data || !data.content) return undefined; return <Content {...data.content} />; }, };
es6/Checkbox/CheckBoxButton.js
yurizhang/ishow
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import CheckBox from './CheckBox'; var CheckboxButton = function (_CheckBox) { _inherits(CheckboxButton, _CheckBox); function CheckboxButton() { _classCallCheck(this, CheckboxButton); return _possibleConstructorReturn(this, (CheckboxButton.__proto__ || Object.getPrototypeOf(CheckboxButton)).apply(this, arguments)); } _createClass(CheckboxButton, [{ key: 'render', value: function render() { var group = this.context.ElCheckboxGroup; return React.createElement( 'label', { style: this.style(), className: this.className('ishowcheckbox-button', group.props.size ? 'ishowcheckbox-button--' + group.props.size : '', { 'is-disabled': this.props.disabled, 'is-checked': this.state.checked, 'is-focus': this.state.focus }) }, React.createElement('input', { className: 'ishowcheckbox-button__original', type: 'checkbox', checked: this.state.checked, disabled: this.props.disabled, onFocus: this.onFocus.bind(this), onBlur: this.onBlur.bind(this), onChange: this.onChange.bind(this) }), React.createElement( 'span', { className: 'ishowcheckbox-button__inner', style: this.state.checked ? { boxShadow: '-1px 0 0 0 ' + group.props.fill, backgroundColor: group.props.fill || '', borderColor: group.props.fill || '', color: group.props.textColor || '' } : {} }, this.state.label || this.props.children ) ); } }]); return CheckboxButton; }(CheckBox); CheckboxButton.elementType = 'CheckboxButton'; export default CheckboxButton;
salt-frontend/react/dashboard/src/components/PortletUpdate.js
syakuis/salt-framework
import React from 'react'; import { connect } from 'react-redux'; import { updatePortlet } from '../actions'; class PortletUpdate extends React.Component { constructor(props) { super(props); this.initDataBind = this.initDataBind.bind(this); this.onUpdatePortlet = this.onUpdatePortlet.bind(this); } state = { ...this.props.dashboard[this.props.idx] } initDataBind(e) { let datatype = e.target.attributes.getNamedItem('datatype'); let value = e.target.value; if (datatype != null) { datatype = datatype.value; } switch(e.target.type) { case 'checkbox': value = e.target.checked; break; default: break; } switch(datatype) { case 'number': value = parseFloat(value); break; case 'boolean': if (typeof value === 'boolean') value = Boolean(value); break; } this.setState({[e.target.name]: value }); } onUpdatePortlet() { this.props.updatePortlet(this.state); this.props.onModalClose(); } render() { return ( <div> <div className="form-group"> <label htmlFor="padding">padding</label> <input type="text" className="form-control" placeholder="padding" name="padding" datatype="number" onChange={this.initDataBind} value={this.state.padding} /> </div> <div className="form-group"> <label htmlFor="static">static</label> <label className="checkbox-inline"> <input type="checkbox" name="static" datatype="boolean" checked={this.state.static} onChange={this.initDataBind} /> 사용 </label> </div> <div className="form-group"> <label htmlFor="draggable">draggable</label> <label className="checkbox-inline"> <input type="checkbox" name="isDraggable" datatype="boolean" onChange={this.initDataBind} checked={this.state.isDraggable} /> 사용 </label> </div> <div className="form-group"> <label htmlFor="resizable">resizable</label> <label className="checkbox-inline"> <input type="checkbox" name="isResizable" datatype="boolean" onChange={this.initDataBind} checked={this.state.isResizable} /> 사용 </label> </div> <button className="btn btn-default" type="button" onClick={this.onUpdatePortlet}>수정</button> </div> ); } } const mapStateToProps = (state) => { return { dashboard: state.portlet.dashboard }; } const mapDispatchToProps = (dispatch) => { return { updatePortlet: (portlet) => dispatch(updatePortlet(portlet)) } } export default PortletUpdate = connect( mapStateToProps, mapDispatchToProps )(PortletUpdate);
pootle/static/js/user/components/UserProfileForm.js
unho/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import { link } from 'autolinker'; import React from 'react'; import FormElement from 'components/FormElement'; import ModelFormMixin from 'mixins/ModelFormMixin'; import Avatar from 'components/Avatar'; // XXX: should probably live somewhere else function linkify(input) { return { __html: link(input), }; } export const UserProfileForm = React.createClass({ propTypes: { onDirty: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, }, mixins: [ModelFormMixin], /* Lifecycle */ componentWillUpdate(nextProps, nextState) { if (nextState.isDirty !== this.state.isDirty) { this.props.onDirty(nextState.isDirty); } }, fields: ['full_name', 'twitter', 'linkedin', 'website', 'bio'], /* Handlers */ handleSuccess(user) { this.props.onSuccess(user); }, /* Layout */ render() { const model = this.getResource(); const { errors } = this.state; const { formData } = this.state; const avatarHelpMsg = gettext( 'To set or change your avatar for your email address ' + '(%(email)s), please go to gravatar.com.' ); const avatarHelp = interpolate(avatarHelpMsg, { email: model.get('email') }, true); return ( <form method="post" id="item-form" autoComplete="off" onSubmit={this.handleFormSubmit} > <div className="fields"> <FormElement label={gettext('Full Name')} placeholder={gettext('Your Full Name')} autoFocus handleChange={this.handleChange} name="full_name" errors={errors.full_name} value={formData.full_name} /> <p> <label>{gettext('Avatar')}</label> <Avatar email={model.get('email')} size={48} /> <span className="helptext" dangerouslySetInnerHTML={linkify(avatarHelp)} /> </p> <p className="divider" /> <FormElement label={gettext('Twitter')} handleChange={this.handleChange} placeholder={gettext('Your Twitter username')} maxLength="15" name="twitter" errors={errors.twitter} value={formData.twitter} /> <FormElement label={gettext('LinkedIn')} handleChange={this.handleChange} placeholder={gettext('Your LinkedIn profile URL')} name="linkedin" errors={errors.linkedin} value={formData.linkedin} /> <FormElement label={gettext('Website')} handleChange={this.handleChange} placeholder={gettext('Your Personal website/blog URL')} name="website" errors={errors.website} value={formData.website} /> <FormElement type="textarea" label={gettext('Short Bio')} handleChange={this.handleChange} placeholder={gettext('Why are you part of our translation project? ' + 'Describe yourself, inspire others!')} name="bio" errors={errors.bio} value={formData.bio} /> </div> <p className="buttons"> <input type="submit" className="btn btn-primary" disabled={!this.state.isDirty} value={gettext('Save')} /> </p> </form> ); }, }); export default UserProfileForm;
components/connected/status/content/gallery/index.js
marrus-sh/mastodon-go
// <ConnectedStatusContentGallery> // =============================== // This component renders the attachments of a status in a nice // gallery. // * * * * * * * // // Imports: // -------- // Package imports. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; // Component imports. import { CommonButton, ConnectedMedia, } from 'themes/mastodon-go/components'; // Stylesheet imports. import './style.scss'; // * * * * * * * // // The component // ------------- // Component definition. export default class ConnectedStatusContentGallery extends React.PureComponent { // Constructor. constructor (props) { super(props); // State. this.state = { visible: !this.props.sensitive }; // Function binding. const { handleToggle } = Object.getPrototypeOf(this); this.handleToggle = handleToggle.bind(this); } // Handles showing and hiding media. handleToggle () { this.setState({ visible: !this.state.visible }); } // Renders. render () { const { handleToggle } = this; const { className, media, sensitive, ℳ, } = this.props; const { visible } = this.state; const computedClass = classNames('MASTODON_GO--CONNECTED--STATUS--CONTENT--GALLERY', 'size-' + media.size, className); // We can only use up to 4 attachments. const useäbleAttachments = media.take(4); // Renders the gallery. return ( <div className={computedClass}> {visible ? ( <CommonButton className='button' icon={visible ? 'eye' : 'eye-slash'} title={ℳ.hideMedia} onClick={handleToggle} /> ) : ( <CommonButton active className='curtain' title={ℳ.hideMedia} onClick={handleToggle} > <span> <strong>{sensitive ? ℳ.sensitive : ℳ.hidden}</strong> {ℳ.clickToView} </span> </CommonButton> )} {visible ? useäbleAttachments.map( attachment => ( <ConnectedMedia key={attachment.get('id')} id={attachment.get('id')} /> ) ) : null} </div> ); } } // Props. ConnectedStatusContentGallery.propTypes = { className: PropTypes.string, media: ImmutablePropTypes.list.isRequired, // A list of media to render in the gallery sensitive: PropTypes.bool, // `true` if the media is sensitive ℳ: PropTypes.func.isRequired, };
fields/types/cloudinaryimage/CloudinaryImageFilter.js
nickhsine/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; var PasswordFilter = React.createClass({ getInitialState () { return { checked: this.props.value || true, }; }, toggleChecked (checked) { this.setState({ checked: checked, }); }, renderToggle () { let options = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false }, ]; return <SegmentedControl equalWidthSegments options={options} value={this.state.checked} onChange={this.toggleChecked} />; }, render () { return this.renderToggle(); }, }); module.exports = PasswordFilter;
client/src/components/UtilComponents/NotFound.js
codefordenver/Circular
import React from 'react'; import { Link } from 'react-router'; const NotFound = () => ( <div className="not-found-container"> <div> <h1>You seem to have gotten lost...</h1> </div> <div> <i className="fa fa-4x fa-recycle loading-spinner slow-spin" /> </div> <div> <Link className="home-section-link" to="/"> Go back to Home Page </Link> </div> </div> ); export default NotFound;
examples/huge-apps/routes/Profile/components/Profile.js
Dodelkin/react-router
import React from 'react' class Profile extends React.Component { render() { return ( <div> <h2>Profile</h2> </div> ) } } export default Profile
src/modules/keywords/components/KeywordCommentList/KeywordCommentList.js
CtrHellenicStudies/Commentary
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import moment from 'moment'; import { compose } from 'react-apollo'; // components import AvatarIcon from '../../../users/components/AvatarIcon'; // lib import createRevisionMarkup from '../../../../lib/createRevisionMarkup'; // graphql import commentersQuery from '../../../commenters/graphql/queries/list'; const KeywordCommentList = (props) => { const { keywordComments } = props; if (!keywordComments || !keywordComments.length) { return ( <div className="comment-outer has-discussion"> <div className="no-results"> This tag has no comments associated with it yet. </div> </div> ); } return ( <div className="comment-outer has-discussion"> {props.keywordComments.map((comment, i) => { const selectedRevision = comment.revisions[comment.revisions.length - 1]; const updated = selectedRevision.updated; const format = 'D MMMM YYYY'; return ( <article key={comment._id} className="comment commentary-comment paper-shadow " > <div className="comment-upper"> <div className="comment-upper-left"> <h2 className="comment-title" style={{margin: 0, padding: 0}}><Link to={`/commentary?_id=${comment._id}`}>{selectedRevision.title}</Link></h2> </div> <div className="comment-upper-right"> {comment.commenters.map((commenter, _i) => { const commenterRecord = props.commentersQuery.loading ? {} : props.commentersQuery.commenters.find(x => x.slug === commenter.slug); if (!commenterRecord) { return null; } return ( <div key={_i} className="comment-author" > <div className="comment-author-text"> <Link to={`/commenters/${commenterRecord.slug}`}> <span className="comment-author-name" style={{margin: 0, textAlign: 'right'}}>{commenterRecord.name}</span> </Link> <span className="comment-date" style={{margin: 0, textAlign: 'right'}}> {moment(updated).format(format)} </span> </div> <div className="comment-author-image-wrap paper-shadow"> <Link to={`/commenters/${commenterRecord.slug}`}> <AvatarIcon avatar={ (commenterRecord && commenterRecord.avatar) ? commenterRecord.avatar.src : null } /> </Link> </div> </div> ); })} </div> </div> <div className="comment-lower"> <div className="comment-body" dangerouslySetInnerHTML={createRevisionMarkup(selectedRevision.text)} /> </div> </article> ); })} </div> ); }; KeywordCommentList.propTypes = { keywordComments: PropTypes.array, }; export default compose( commentersQuery )(KeywordCommentList);
packages/material-ui-icons/src/LocalDining.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let LocalDining = props => <SvgIcon {...props}> <path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z" /> </SvgIcon>; LocalDining = pure(LocalDining); LocalDining.muiName = 'SvgIcon'; export default LocalDining;
src/Components/RichEditor/index.js
sqhtiamo/zaro
import React, { Component } from 'react'; import { PropTypes } from 'prop-types'; import Loading from '../Loading'; class RichEditor extends Component { static genStyle(tags = []) { const res = {}; const styles = [ 'color', 'font-size', 'font-family', 'position', 'display', 'font-weight', 'cursor', 'letter-spacing', 'line-height', 'vertical-align', 'text-align', 'width', 'height', 'padding', 'padding-top', 'padding-left', 'padding-right', 'padding-bottom', 'margin', 'margin-top', 'margin-left', 'margin-right', 'margin-bottom', 'border', 'border-top', 'border-left', 'border-right', 'border-bottom', 'border-collapse', 'border-color', 'border-collapse', 'background', 'background-color', 'word-break', 'list-style-type' ]; for (let i = 0; i < tags.length; i++) { res[tags[i]] = styles; } return res; } static genAttr(tags = []) { const res = {}; const attrs = [ 'src', 'alt', 'width', 'height', 'title', 'color', 'class', 'align', 'valign', 'size', 'bgColor', 'cols', 'rows', 'colspan', 'rowspan', 'align', 'size', 'cellpadding', 'cellspacing', 'border', 'nowrap' ]; for (let i = 0; i < tags.length; i++) { res[tags[i]] = attrs; } return res; } constructor(props) { super(props); this.state = { isFull: false, isLoading: true, }; this.showModal = this.showModal.bind(this); this.hideModal = this.hideModal.bind(this); this.htmlTags = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b', 'strong', 'i', 'em', 'ul', 'ol', 'li', 'font', 'br', 'p', 'sub', 'sup', 'del', 'hr', 'table', 'th', 'tr', 'thead', 'tbody', 'td', 'colgroup', 'col', 'div', 'pre', 'dl', 'dt', 'dd', 'a', 'span', 'code', 'blockquote', 'header', 'footer', 'nav', 'aside', 'section', 'figure', 'time', 'cite', ]; } componentDidMount() { const { editorOnload } = this.props; require.ensure([], (require) => { window.jquery = require('jquery/dist/jquery'); this.Simditor = require('simditor'); this.style = require('./simditor.css'); this.setState({ isLoading: false }); this.initEditor(); // 确保已经载入 setTimeout(() => { editorOnload(); }); }); } componentWillUnmount() { this.editor.destroy(); } getContent() { return this.editor.getValue(); } setContent(v) { this.editor.setValue(v); } initEditor() { const textbox = this.textarea; this.editor = new this.Simditor({ textarea: window.jquery(textbox), upload: false, toolbarFloat: false, toolbar: [ 'title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', 'ol', 'ul', 'blockquote', // 'code', 'table', // 'link', 'hr', 'indent', 'outdent', 'alignment' ], allowedTags: this.htmlTags, allowedAttributes: RichEditor.genAttr(this.htmlTags), allowedStyles: RichEditor.genStyle(this.htmlTags) }); this.editor.on('valuechanged', () => { this.props.change(this.getContent()); }); } showModal() { this.setState({ isFull: true }); document.body.style.overflow = 'hidden'; // 编辑器全屏 window.jquery('.simditor').addClass('full'); } hideModal() { this.setState({ isFull: false }); document.body.style.overflow = 'auto'; window.jquery('.simditor').removeClass('full'); } render() { const { isFull, isLoading } = this.state; if (isLoading) { return ( <Loading /> ); } return ( <div> <div onClick={this.hideModal} className={isFull ? 'full editor-modal' : 'editor-modal'} /> <textarea ref={(item) => { this.textarea = item; }} /> </div> ); } } RichEditor.propTypes = { change: PropTypes.func, editorOnload: PropTypes.func, }; RichEditor.defaultProps = { change: () => {}, editorOnload: () => {} }; export default RichEditor;
app/javascript/mastodon/features/compose/components/upload_progress.js
hugogameiro/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { FormattedMessage } from 'react-intl'; export default class UploadProgress extends React.PureComponent { static propTypes = { active: PropTypes.bool, progress: PropTypes.number, }; render () { const { active, progress } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <i className='fa fa-upload' /> </div> <div className='upload-progress__message'> <FormattedMessage id='upload_progress.label' defaultMessage='Uploading...' /> <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } }
app/javascript/mastodon/features/explore/results.js
koba-lab/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { expandSearch } from 'mastodon/actions/search'; import Account from 'mastodon/containers/account_container'; import Status from 'mastodon/containers/status_container'; import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag'; import { List as ImmutableList } from 'immutable'; import LoadMore from 'mastodon/components/load_more'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = state => ({ isLoading: state.getIn(['search', 'isLoading']), results: state.getIn(['search', 'results']), }); const appendLoadMore = (id, list, onLoadMore) => { if (list.size >= 5) { return list.push(<LoadMore key={`${id}-load-more`} visible onClick={onLoadMore} />); } else { return list; } }; const renderAccounts = (results, onLoadMore) => appendLoadMore('accounts', results.get('accounts', ImmutableList()).map(item => ( <Account key={`account-${item}`} id={item} /> )), onLoadMore); const renderHashtags = (results, onLoadMore) => appendLoadMore('hashtags', results.get('hashtags', ImmutableList()).map(item => ( <Hashtag key={`tag-${item.get('name')}`} hashtag={item} /> )), onLoadMore); const renderStatuses = (results, onLoadMore) => appendLoadMore('statuses', results.get('statuses', ImmutableList()).map(item => ( <Status key={`status-${item}`} id={item} /> )), onLoadMore); export default @connect(mapStateToProps) class Results extends React.PureComponent { static propTypes = { results: ImmutablePropTypes.map, isLoading: PropTypes.bool, multiColumn: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; state = { type: 'all', }; handleSelectAll = () => this.setState({ type: 'all' }); handleSelectAccounts = () => this.setState({ type: 'accounts' }); handleSelectHashtags = () => this.setState({ type: 'hashtags' }); handleSelectStatuses = () => this.setState({ type: 'statuses' }); handleLoadMoreAccounts = () => this.loadMore('accounts'); handleLoadMoreStatuses = () => this.loadMore('statuses'); handleLoadMoreHashtags = () => this.loadMore('hashtags'); loadMore (type) { const { dispatch } = this.props; dispatch(expandSearch(type)); } render () { const { isLoading, results } = this.props; const { type } = this.state; let filteredResults = ImmutableList(); if (!isLoading) { switch(type) { case 'all': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts), renderHashtags(results, this.handleLoadMoreHashtags), renderStatuses(results, this.handleLoadMoreStatuses)); break; case 'accounts': filteredResults = filteredResults.concat(renderAccounts(results, this.handleLoadMoreAccounts)); break; case 'hashtags': filteredResults = filteredResults.concat(renderHashtags(results, this.handleLoadMoreHashtags)); break; case 'statuses': filteredResults = filteredResults.concat(renderStatuses(results, this.handleLoadMoreStatuses)); break; } if (filteredResults.size === 0) { filteredResults = ( <div className='empty-column-indicator'> <FormattedMessage id='search_results.nothing_found' defaultMessage='Could not find anything for these search terms' /> </div> ); } } return ( <React.Fragment> <div className='account__section-headline'> <button onClick={this.handleSelectAll} className={type === 'all' && 'active'}><FormattedMessage id='search_results.all' defaultMessage='All' /></button> <button onClick={this.handleSelectAccounts} className={type === 'accounts' && 'active'}><FormattedMessage id='search_results.accounts' defaultMessage='People' /></button> <button onClick={this.handleSelectHashtags} className={type === 'hashtags' && 'active'}><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></button> <button onClick={this.handleSelectStatuses} className={type === 'statuses' && 'active'}><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></button> </div> <div className='explore__search-results'> {isLoading ? <LoadingIndicator /> : filteredResults} </div> </React.Fragment> ); } }
app/javascript/mastodon/features/ui/components/columns_area.js
pfm-eyesightjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl } from 'react-intl'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeableViews from 'react-swipeable-views'; import { links, getIndex, getLink } from './tabs_bar'; import BundleContainer from '../containers/bundle_container'; import ColumnLoading from './column_loading'; import BundleColumnError from './bundle_column_error'; import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses } from '../../ui/util/async-components'; import detectPassiveEvents from 'detect-passive-events'; import { scrollRight } from '../../../scroll'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, 'FAVOURITES': FavouritedStatuses, }; @component => injectIntl(component, { withRef: true }) export default class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, columns: ImmutablePropTypes.list.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; state = { shouldAnimate: false, } componentWillReceiveProps() { this.setState({ shouldAnimate: false }); } componentDidMount() { if (!this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.setState({ shouldAnimate: true }); } componentWillUpdate(nextProps) { if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } componentDidUpdate(prevProps) { if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } this.lastIndex = getIndex(this.context.router.history.location.pathname); this.setState({ shouldAnimate: true }); } componentWillUnmount () { if (!this.props.singleColumn) { this.node.removeEventListener('wheel', this.handleWheel); } } handleChildrenContentChange() { if (!this.props.singleColumn) { scrollRight(this.node, this.node.scrollWidth - window.innerWidth); } } handleSwipe = (index) => { this.pendingIndex = index; const nextLinkTranslationId = links[index].props['data-preview-title-id']; const currentLinkSelector = '.tabs-bar__link.active'; const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`; // HACK: Remove the active class from the current link and set it to the next one // React-router does this for us, but too late, feeling laggy. document.querySelector(currentLinkSelector).classList.remove('active'); document.querySelector(nextLinkSelector).classList.add('active'); } handleAnimationEnd = () => { if (typeof this.pendingIndex === 'number') { this.context.router.history.push(getLink(this.pendingIndex)); this.pendingIndex = null; } } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = (node) => { this.node = node; } renderView = (link, index) => { const columnIndex = getIndex(this.context.router.history.location.pathname); const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] }); const icon = link.props['data-preview-icon']; const view = (index === columnIndex) ? React.cloneElement(this.props.children) : <ColumnLoading title={title} icon={icon} />; return ( <div className='columns-area' key={index}> {view} </div> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { columns, children, singleColumn } = this.props; const { shouldAnimate } = this.state; const columnIndex = getIndex(this.context.router.history.location.pathname); this.pendingIndex = null; if (singleColumn) { return columnIndex !== -1 ? ( <ReactSwipeableViews index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}> {links.map(this.renderView)} </ReactSwipeableViews> ) : <div className='columns-area'>{children}</div>; } return ( <div className='columns-area' ref={this.setRef}> {columns.map(column => { const params = column.get('params', null) === null ? null : column.get('params').toJS(); return ( <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading} error={this.renderError}> {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />} </BundleContainer> ); })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
fields/types/Field.js
davibe/keystone
import _ from 'underscore'; import classnames from 'classnames'; import evalDependsOn from '../utils/evalDependsOn.js'; import React from 'react'; import { Button, FormField, FormInput, FormNote } from 'elemental'; function validateSpec(spec) { if (!spec) spec = {}; if (!_.isObject(spec.supports)) { spec.supports = {}; } if (!spec.focusTargetRef) { spec.focusTargetRef = 'focusTarget'; } return spec; } var Base = module.exports.Base = { getInitialState () { return {}; }, getDefaultProps () { return { inputProps: {}, labelProps: {}, valueProps: {}, size: 'full' }; }, valueChanged (event) { this.props.onChange({ path: this.props.path, value: event.target.value }); }, shouldCollapse () { return this.props.collapse && !this.props.value; }, shouldRenderField () { if (!this.props.noedit) return true; if (this.props.mode === 'create' && this.props.initial) return true; return false; }, focus () { if (!this.refs[this.spec.focusTargetRef]) return; this.refs[this.spec.focusTargetRef].getDOMNode().focus(); }, renderNote () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderField () { var props = _.extend(this.props.inputProps, { autoComplete: 'off', name: this.props.path, onChange: this.valueChanged, ref: 'focusTarget', value: this.props.value }); return <FormInput {...props} />; }, renderValue () { return <FormInput noedit>{this.props.value}</FormInput>; }, renderUI () { var wrapperClassName = classnames( ('field-type-' + this.props.type), this.props.className ); return ( <FormField label={this.props.label} className={wrapperClassName} htmlFor={this.props.path}> <div className={'FormField__inner field-size-' + this.props.size}> {this.shouldRenderField() ? this.renderField() : this.renderValue()} </div> {this.renderNote()} </FormField> ); } }; var Mixins = module.exports.Mixins = { Collapse: { componentWillMount () { this.setState({ isCollapsed: this.shouldCollapse() }); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.focus(); } }, uncollapse () { this.setState({ isCollapsed: false }); }, renderCollapse () { if (!this.shouldRenderField()) return null; return ( <FormField> <Button type="link" className="collapsed-field-label" onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</Button> </FormField> ); } } }; module.exports.create = function(spec) { spec = validateSpec(spec); var excludeBaseMethods = []; var field = { spec: spec, displayName: spec.displayName, mixins: [Mixins.Collapse], render () { if (!evalDependsOn(this.props.dependsOn, this.props.values)) { return null; } if (this.state.isCollapsed) { return this.renderCollapse(); } return this.renderUI(); } }; if (spec.mixins) { _.each(spec.mixins, function(mixin) { _.each(mixin, function(method, name) { if (Base[name]) excludeBaseMethods.push(name); }); }); } _.extend(field, _.omit(Base, excludeBaseMethods)); _.extend(field, _.omit(spec, 'mixins')); if (_.isArray(spec.mixins)) { field.mixins = field.mixins.concat(spec.mixins); } return React.createClass(field); };
examples/todomvc/containers/Root.dev.js
alexkuz/redux-devtools
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import TodoApp from './TodoApp'; import DevTools from './DevTools'; export default class Root extends Component { render() { const { store } = this.props; return ( <Provider store={store}> <div> <TodoApp /> <DevTools /> </div> </Provider> ); } }
example/src/screens/types/Notification.js
junedomingo/react-native-navigation
import React from 'react'; import {StyleSheet, View, Text, Dimensions, Button} from 'react-native'; class Notification extends React.Component { render() { return ( <View style={styles.container}> <Text style={styles.title}>In-App Notification</Text> <Text style={styles.content}>You have 10 unread notifications!</Text> </View> ); } } const styles = StyleSheet.create({ container: { height: 100, backgroundColor: '#ff505c', padding: 16, margin: 10, }, title: { fontSize: 18, textAlign: 'center', }, content: { textAlign: 'center', marginTop: 10, }, }); export default Notification;
src/TextField/TextFieldHint.js
ichiohta/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import transitions from '../styles/transitions'; function getStyles(props) { const { muiTheme: { textField: { hintColor, }, }, show, } = props; return { root: { position: 'absolute', opacity: show ? 1 : 0, color: hintColor, transition: transitions.easeOut(), bottom: 12, }, }; } const TextFieldHint = (props) => { const { muiTheme: { prepareStyles, }, style, text, } = props; const styles = getStyles(props); return ( <div style={prepareStyles(Object.assign(styles.root, style))}> {text} </div> ); }; TextFieldHint.propTypes = { /** * @ignore * The material-ui theme applied to this component. */ muiTheme: PropTypes.object.isRequired, /** * True if the hint text should be visible. */ show: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, /** * The hint text displayed. */ text: PropTypes.node, }; TextFieldHint.defaultProps = { show: true, }; export default TextFieldHint;
src/svg-icons/social/people.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPeople = (props) => ( <SvgIcon {...props}> <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/> </SvgIcon> ); SocialPeople = pure(SocialPeople); SocialPeople.displayName = 'SocialPeople'; SocialPeople.muiName = 'SvgIcon'; export default SocialPeople;
src/components/item/view/ItemActionPanel.js
katima-g33k/blu-react-desktop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ActionPanel } from '../../general'; import i18n from '../../../lib/i18n'; import StatusButton from '../../../containers/StatusButtonContainer'; export default class ItemActionPanel extends Component { static propTypes = { canDelete: PropTypes.bool.isRequired, handleDelete: PropTypes.func.isRequired, handleReserve: PropTypes.func.isRequired, handleUpdateStorage: PropTypes.func.isRequired, modify: PropTypes.func.isRequired, userIsAdmin: PropTypes.bool.isRequired, }; userActions = [ { label: i18n('ItemView.actions.modify'), onClick: this.props.modify, }, { customComponent: (<StatusButton />), }, { label: i18n('ItemView.actions.storage'), onClick: this.props.handleUpdateStorage, }, { label: i18n('ItemView.actions.reserve'), onClick: this.props.handleReserve, }, ]; adminActions = [{ disabled: this.props.canDelete, label: i18n('ItemView.actions.delete'), onClick: this.props.handleDelete, style: 'danger', }]; actions = [ ...this.userActions, ...(this.props.userIsAdmin ? this.adminActions : []), ]; render() { return (<ActionPanel actions={this.actions} />); } }
Neos.Media.Browser/packages/neos-media-browser/src/Variants/Variants.js
daniellienert/neos-development-collection
import React from 'react'; import Variant from './Variant'; export default class Variants extends React.PureComponent { render() { const {variants, onRequestCrop} = this.props; const renderedVariants = variants.map((variantInformation) => <Variant onRequestCrop={onRequestCrop} key={variantInformation.persistenceIdentifier} {...variantInformation} />); return ( <ul className="neos-thumbnails asset-list"> {renderedVariants} </ul> ) } }
client/src/transforms/TreeDropdownField/moveTreeDropdownField.js
open-sausages/silverstripe-asset-admin
import React from 'react'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { findTreeByPath } from 'components/TreeDropdownField/TreeDropdownField'; /** * Enables a treepdropdown field to have individually disabled items */ const disabledTreeDropdownField = (TreeDropdownField) => (props) => { /* eslint-disable react/prop-types */ const { disabledIDs } = props; const find = props.findTreeByPath || findTreeByPath; /* eslint-enable react/prop-types */ const newProps = { ...props, findTreeByPath(tree, visible) { const visibleTree = find(tree, visible); const pathDisabled = visible.some(id => disabledIDs.includes(id)); return visibleTree ? { ...visibleTree, children: visibleTree.children.map(child => ({ ...child, disabled: pathDisabled || disabledIDs.includes(child.id), })), } : null; }, }; return <TreeDropdownField {...newProps} />; }; /* * Ensure selected files can't also be selected as move target */ const moveTreeDropdownField = compose( connect( state => ({ disabledIDs: state.assetAdmin.gallery.selectedFiles, }) ), disabledTreeDropdownField ); export { disabledTreeDropdownField }; export default moveTreeDropdownField;
node_modules/@material-ui/core/es/internal/svg-icons/CheckBoxOutlineBlank.js
pcclarke/civ-techs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" }), 'CheckBoxOutlineBlank');
demo/src/index.js
insin/react-octicon
import React from 'react' import {render} from 'react-dom' import Demo from './Demo' render(<Demo/>, document.querySelector('#demo'))
projects/react-redux/sample/app/src/index.js
stanleygomes/stanleygomes.github.io
import React from 'react'; import { render } from 'react-dom'; import router from './utils/router'; import '../styles/styles.scss'; const rootElement = document.getElementById('app'); render(router, rootElement);
src/components/ControlPanel/ControlPanel.js
bocasfx/Q
import React from 'react'; import './ControlPanel.css'; import SelectorPanel from './SelectorPanel'; import EditorPanel from './EditorPanel'; import config from '../../config/config'; class ControlPanel extends React.Component { constructor(props) { super(props); this.style = { width: config.controlPanel.width, }; } render() { return ( <div className="control-panel-container" style={this.style}> <SelectorPanel /> <EditorPanel /> </div> ); } } export default ControlPanel;
src/svg-icons/content/add-circle.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAddCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/> </SvgIcon> ); ContentAddCircle = pure(ContentAddCircle); ContentAddCircle.displayName = 'ContentAddCircle'; ContentAddCircle.muiName = 'SvgIcon'; export default ContentAddCircle;
docs/src/examples/elements/Header/Types/HeaderExampleContent.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Header } from 'semantic-ui-react' const HeaderExampleContent = () => ( <div> <Header size='huge'>Huge Header</Header> <Header size='large'>Large Header</Header> <Header size='medium'>Medium Header</Header> <Header size='small'>Small Header</Header> <Header size='tiny'>Tiny Header</Header> </div> ) export default HeaderExampleContent
react/features/screen-share/components/ShareAudioDialog.js
gpolitis/jitsi-meet
// @flow import { Checkbox } from '@atlaskit/checkbox'; import React, { Component } from 'react'; import type { Dispatch } from 'redux'; import { Dialog } from '../../base/dialog'; import { translate } from '../../base/i18n'; import { connect } from '../../base/redux'; import { updateSettings, shouldHideShareAudioHelper } from '../../base/settings'; import { toggleScreensharing } from '../../base/tracks'; /** * The type of the React {@code Component} props of {@link ShareAudioDialog}. */ export type Props = { /** * The redux {@code dispatch} function. */ dispatch: Dispatch<any>, /** * Boolean stored in local storage that determines whether or not the dialog will be displayed again. */ _shouldHideShareAudioHelper: boolean, /** * Invoked to obtain translated strings. */ t: Function }; /** * Component that displays the audio screen share helper dialog. */ class ShareAudioDialog extends Component<Props> { /** * Instantiates a new component. * * @inheritdoc */ constructor(props) { super(props); this._onContinue = this._onContinue.bind(this); this._onSelectHideShareAudioHelper = this._onSelectHideShareAudioHelper.bind(this); } _onContinue: () => boolean; /** * Continue the normal screen sharing flow when the user clicks continue. * * @returns {boolean} */ _onContinue() { // Pass undefined as the first parameter so the underlying logic decides weather or not to stop screen sharing. this.props.dispatch(toggleScreensharing(undefined, true)); return true; } _onSelectHideShareAudioHelper: (Object) => void; /** * Callback invoked when the hide audio helper checkbox has been selected. This setting will be persisted in * the local storage, thus the dialog won't be displayed again. * * @param {Object} e - The key event to handle. * @returns {void} */ _onSelectHideShareAudioHelper({ target: { checked } }) { this.props.dispatch(updateSettings({ hideShareAudioHelper: checked })); } /** * Implements {@Component#render}. * * @inheritdoc */ render() { const { t } = this.props; return ( <Dialog hideCancelButton = { false } okKey = { t('dialog.shareAudio') } onSubmit = { this._onContinue } titleKey = { t('dialog.shareAudioTitle') } width = { 'medium' } > <div className = 'share-audio-dialog'> <img className = 'share-audio-animation' src = 'images/share-audio.gif' /> <Checkbox isChecked = { this.props._shouldHideShareAudioHelper } label = { t('dialog.hideShareAudioHelper') } name = 'hide-share-audio-helper' // eslint-disable-next-line react/jsx-no-bind onChange = { this._onSelectHideShareAudioHelper } /> </div> </Dialog> ); } } /** * Maps part of the Redux state to the props of this component. * * @param {Object} state - The Redux state. * @private * @returns {Props} */ function _mapStateToProps(state: Object): $Shape<Props> { return { _shouldHideShareAudioHelper: shouldHideShareAudioHelper(state) }; } export default translate(connect(_mapStateToProps)(ShareAudioDialog));