path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/Ratio.js
tomek-f/tomekf
import React, { Component } from 'react'; import ratio from 'cmnjs/number/ratio'; import styles from './Ratio.module.scss'; class Ratio extends Component { state = { a: 10, b: 20, c: 5, x: 10, }; onChange = ({ target: { name, value } }) => { value = parseInt(value, 10); if (Number.isNaN(value)) { return; } const { a, b, c } = this.state; const temp = { a, b, c, [name]: value, }; this.setState({ [name]: value, x: ratio(temp.a, temp.b, temp.c), }); }; render() { const { a, b, c, x, } = this.state; return ( <div className={styles.root}> <h1> Ratio </h1> <div>a - b</div> <div>c - x</div> <div>x = (b * c) / a</div> <br /> <span>a:</span> <input name="a" value={a} type="number" onChange={this.onChange} /> <span>-</span> <span>b:</span> <input name="b" value={b} type="number" onChange={this.onChange} /> <br /> <span>c:</span> <input name="c" value={c} type="number" onChange={this.onChange} /> <span>-</span> <span>x:</span> <input name="x" value={x} type="text" readOnly /> </div> ); } } export default Ratio;
src/route/notification/promotion-step2.js
simors/yjbAdmin
import React from 'react'; import {connect} from 'react-redux'; import {Row, Col, Icon, Button} from 'antd'; import {action} from './redux'; import Result from '../../component/Result'; class System extends React.Component { constructor(props) { super(props); } onClick = () => { this.props.updateStep({curStep: 1}); }; render() { const actions = ( <div> <Button type="primary" onClick={this.onClick}> 返回 </Button> </div> ); return ( <Result type="success" title="发送成功" actions={actions} /> ); } } const mapDispatchToProps = { ...action, }; export default connect(null, mapDispatchToProps)(System);
js/Nux/ExperienceNuxApp.js
jolicloud/exponent
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule ExperienceNuxApp */ 'use strict'; import React from 'react'; import NuxContextualMenuOverlay from 'NuxContextualMenuOverlay'; export default class ExperienceNuxApp extends React.Component { render() { return ( <NuxContextualMenuOverlay /> ); } }
src/svg-icons/notification/network-locked.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationNetworkLocked = (props) => ( <SvgIcon {...props}> <path d="M19.5 10c.17 0 .33.03.5.05V1L1 20h13v-3c0-.89.39-1.68 1-2.23v-.27c0-2.48 2.02-4.5 4.5-4.5zm2.5 6v-1.5c0-1.38-1.12-2.5-2.5-2.5S17 13.12 17 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z"/> </SvgIcon> ); NotificationNetworkLocked = pure(NotificationNetworkLocked); NotificationNetworkLocked.displayName = 'NotificationNetworkLocked'; NotificationNetworkLocked.muiName = 'SvgIcon'; export default NotificationNetworkLocked;
src/components/menu_bar.js
tszyszko1/Epicodezadanie
import React from 'react'; import { Link } from 'react-router-dom'; import AppBar from 'material-ui/AppBar'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import MenuItem from 'material-ui/MenuItem'; import Divider from 'material-ui/Divider'; const MenuBar = (props) => { const Dropdown = (props) => ( <IconMenu {...props} iconButtonElement={ <IconButton><MoreVertIcon /></IconButton> } targetOrigin={{horizontal: 'right', vertical: 'top'}} anchorOrigin={{horizontal: 'right', vertical: 'top'}} > <MenuItem primaryText="Lista Projektów" containerElement={<Link to="/" />} /> <Divider /> <MenuItem primaryText="Nowy Projekt" containerElement={<Link to="/projekt/nowy" />} /> <MenuItem primaryText="Procedury" containerElement={<Link to="/procedury" />} /> </IconMenu> ); return ( <AppBar title={props.title} iconElementLeft={<Dropdown />} /> ); } export default MenuBar;
src/stories/Button.js
StormBlade97/BaeCountdown
import React from 'react'; const buttonStyles = { border: '1px solid #eee', borderRadius: 3, backgroundColor: '#FFFFFF', cursor: 'pointer', fontSize: 15, padding: '3px 10px', margin: 10, }; const Button = ({ children, onClick }) => ( <button style={buttonStyles} onClick={onClick} > {children} </button> ); Button.propTypes = { children: React.PropTypes.string.isRequired, onClick: React.PropTypes.func, }; export default Button;
src/Table/TableHeader.js
rscnt/material-ui
import React from 'react'; import Checkbox from '../Checkbox'; import TableHeaderColumn from './TableHeaderColumn'; function getStyles(props, context) { const {tableHeader} = context.muiTheme; return { root: { borderBottom: `1px solid ${tableHeader.borderColor}`, }, }; } class TableHeader extends React.Component { static muiName = 'TableHeader'; static propTypes = { /** * Controls whether or not header rows should be * adjusted for a checkbox column. If the select all * checkbox is true, this property will not influence * the number of columns. This is mainly useful for * "super header" rows so that the checkbox column * does not create an offset that needs to be accounted * for manually. */ adjustForCheckbox: React.PropTypes.bool, /** * Children passed to table header. */ children: React.PropTypes.node, /** * The css class name of the root element. */ className: React.PropTypes.string, /** * Controls whether or not the select all checkbox is displayed. */ displaySelectAll: React.PropTypes.bool, /** * If set to true, the select all button will be interactable. * If set to false, the button will not be interactable. * To hide the checkbox, set displaySelectAll to false. */ enableSelectAll: React.PropTypes.bool, /** * @ignore * Callback when select all has been checked. */ onSelectAll: React.PropTypes.func, /** * @ignore * True when select all has been checked. */ selectAllSelected: React.PropTypes.bool, /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, }; static defaultProps = { adjustForCheckbox: true, displaySelectAll: true, enableSelectAll: true, selectAllSelected: false, }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; createSuperHeaderRows() { const numChildren = React.Children.count(this.props.children); if (numChildren === 1) return undefined; const superHeaders = []; for (let index = 0; index < numChildren - 1; index++) { const child = this.props.children[index]; if (!React.isValidElement(child)) continue; const props = { key: `sh${index}`, rowNumber: index, }; superHeaders.push(this.createSuperHeaderRow(child, props)); } if (superHeaders.length) return superHeaders; } createSuperHeaderRow(child, props) { const children = []; if (this.props.adjustForCheckbox) { children.push(this.getCheckboxPlaceholder(props)); } React.Children.forEach(child.props.children, (child) => { children.push(child); }); return React.cloneElement(child, props, children); } createBaseHeaderRow() { const numChildren = React.Children.count(this.props.children); const child = (numChildren === 1) ? this.props.children : this.props.children[numChildren - 1]; const props = { key: `h${numChildren}`, rowNumber: numChildren, }; const children = [this.getSelectAllCheckboxColumn(props)]; React.Children.forEach(child.props.children, (child) => { children.push(child); }); return React.cloneElement( child, props, children ); } getCheckboxPlaceholder(props) { if (!this.props.adjustForCheckbox) return null; const key = `hpcb${props.rowNumber}`; return <TableHeaderColumn key={key} style={{width: 24}} />; } getSelectAllCheckboxColumn(props) { if (!this.props.displaySelectAll) return this.getCheckboxPlaceholder(props); const checkbox = ( <Checkbox key="selectallcb" name="selectallcb" value="selected" disabled={!this.props.enableSelectAll} checked={this.props.selectAllSelected} onCheck={this.handleCheckAll} /> ); const key = `hpcb${props.rowNumber}`; return ( <TableHeaderColumn key={key} style={{width: 24}}> {checkbox} </TableHeaderColumn> ); } handleCheckAll = (event, checked) => { if (this.props.onSelectAll) this.props.onSelectAll(checked); }; render() { const { className, style, } = this.props; const {prepareStyles} = this.context.muiTheme; const styles = getStyles(this.props, this.context); const superHeaderRows = this.createSuperHeaderRows(); const baseHeaderRow = this.createBaseHeaderRow(); return ( <thead className={className} style={prepareStyles(Object.assign(styles.root, style))}> {superHeaderRows} {baseHeaderRow} </thead> ); } } export default TableHeader;
lib/components/MapPolyline.js
j0ergo/react-native-maps
import PropTypes from 'prop-types'; import React from 'react'; import { ViewPropTypes, } from 'react-native'; import decorateMapComponent, { USES_DEFAULT_IMPLEMENTATION, SUPPORTED, } from './decorateMapComponent'; const propTypes = { ...ViewPropTypes, /** * An array of coordinates to describe the polygon */ coordinates: PropTypes.arrayOf(PropTypes.shape({ /** * Latitude/Longitude coordinates */ latitude: PropTypes.number.isRequired, longitude: PropTypes.number.isRequired, })), /** * Callback that is called when the user presses on the polyline */ onPress: PropTypes.func, /* Boolean to allow a polyline to be tappable and use the * onPress function */ tappable: PropTypes.bool, /** * The fill color to use for the path. */ fillColor: PropTypes.string, /** * The stroke width to use for the path. */ strokeWidth: PropTypes.number, /** * The stroke color to use for the path. */ strokeColor: PropTypes.string, /** * The order in which this tile overlay is drawn with respect to other overlays. An overlay * with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays * with the same z-index is arbitrary. The default zIndex is 0. * * @platform android */ zIndex: PropTypes.number, /** * The line cap style to apply to the open ends of the path. * The default style is `round`. * * @platform ios */ lineCap: PropTypes.oneOf([ 'butt', 'round', 'square', ]), /** * The line join style to apply to corners of the path. * The default style is `round`. * * @platform ios */ lineJoin: PropTypes.oneOf([ 'miter', 'round', 'bevel', ]), /** * The limiting value that helps avoid spikes at junctions between connected line segments. * The miter limit helps you avoid spikes in paths that use the `miter` `lineJoin` style. If * the ratio of the miter length—that is, the diagonal length of the miter join—to the line * thickness exceeds the miter limit, the joint is converted to a bevel join. The default * miter limit is 10, which results in the conversion of miters whose angle at the joint * is less than 11 degrees. * * @platform ios */ miterLimit: PropTypes.number, /** * Boolean to indicate whether to draw each segment of the line as a geodesic as opposed to * straight lines on the Mercator projection. A geodesic is the shortest path between two * points on the Earth's surface. The geodesic curve is constructed assuming the Earth is * a sphere. * * @platform android */ geodesic: PropTypes.bool, /** * The offset (in points) at which to start drawing the dash pattern. * * Use this property to start drawing a dashed line partway through a segment or gap. For * example, a phase value of 6 for the patter 5-2-3-2 would cause drawing to begin in the * middle of the first gap. * * The default value of this property is 0. * * @platform ios */ lineDashPhase: PropTypes.number, /** * An array of numbers specifying the dash pattern to use for the path. * * The array contains one or more numbers that indicate the lengths (measured in points) of the * line segments and gaps in the pattern. The values in the array alternate, starting with the * first line segment length, followed by the first gap length, followed by the second line * segment length, and so on. * * This property is set to `null` by default, which indicates no line dash pattern. * * @platform ios */ lineDashPattern: PropTypes.arrayOf(PropTypes.number), }; const defaultProps = { strokeColor: '#000', strokeWidth: 1, }; class MapPolyline extends React.Component { setNativeProps(props) { this.polyline.setNativeProps(props); } render() { const AIRMapPolyline = this.getAirComponent(); return ( <AIRMapPolyline {...this.props} ref={ref => { this.polyline = ref; }} /> ); } } MapPolyline.propTypes = propTypes; MapPolyline.defaultProps = defaultProps; module.exports = decorateMapComponent(MapPolyline, { componentType: 'Polyline', providers: { google: { ios: SUPPORTED, android: USES_DEFAULT_IMPLEMENTATION, }, }, });
reloby-app-client/src/components/AppliedRoute.js
hwclass/reloby
import React from 'react'; import { Route } from 'react-router-dom'; export default ({ component: C, props: cProps, ...rest }) => ( <Route {...rest} render={ props => <C {...props} {...cProps} /> } /> );
app/main.js
ellheat/devtalk-testing-exercise
/** * 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 injectTapEventPlugin from 'react-tap-event-plugin'; import FontFaceObserver from 'fontfaceobserver'; import { useScroll } from 'react-router-scroll'; import 'normalize.css/normalize.css'; import './main.scss'; // Import selector for `syncHistoryWithStore` import { selectLocationState } from './modules/router/router.selectors'; import configureStore from './modules/store'; // Import routes import routes from './routes'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Needed for onTouchTap // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); // 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: selectLocationState(), }); if (process.env.NODE_ENV) { const DevToolsComponent = require('./utils/devtools.component'); const devToolsRoot = window.document.createElement('div'); window.document.body.appendChild(devToolsRoot); ReactDOM.render( <Provider store={store}> <DevToolsComponent /> </Provider>, devToolsRoot ); } const render = () => { ReactDOM.render( <Provider store={store}> <Router history={history} routes={routes} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </Provider>, document.getElementById('app') ); }; // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(require('intl')); })) .then(() => Promise.all([ require('intl/locale-data/jsonp/en.js'), require('intl/locale-data/jsonp/de.js'), ])) .then(() => render()) .catch((err) => { throw err; }); } else { render(); } /* istanbul ignore next */ if (module.hot) { module.hot.accept('./routes', () => { render(); }); } // 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, import/no-extraneous-dependencies }
docs/app/Examples/collections/Table/Variations/TableExampleInvertedColors.js
clemensw/stardust
import React from 'react' import { Table } from 'semantic-ui-react' const colors = [ 'red', 'orange', 'yellow', 'olive', 'green', 'teal', 'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black', ] const TableExampleInvertedColors = () => ( <div> {colors.map(color => ( <Table color={color} key={color} inverted> <Table.Header> <Table.Row> <Table.HeaderCell>Food</Table.HeaderCell> <Table.HeaderCell>Calories</Table.HeaderCell> <Table.HeaderCell>Protein</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>Apples</Table.Cell> <Table.Cell>200</Table.Cell> <Table.Cell>0g</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Orange</Table.Cell> <Table.Cell>310</Table.Cell> <Table.Cell>0g</Table.Cell> </Table.Row> </Table.Body> </Table> ))} </div> ) export default TableExampleInvertedColors
test/helpers/fullRenderHelper.js
abbr/ShowPreper
import { mount } from 'enzyme' import App from 'components/app' import Impress from 'components/show/impress' import React from 'react' const AppMap = { App, Impress } let appWrapper export default function(appNm){ let TheApp = AppMap[appNm] appWrapper && appWrapper.unmount() appWrapper = mount(<TheApp />, { attachTo: document.getElementById('app') }) return appWrapper }
src/svg-icons/device/battery-std.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryStd = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryStd = pure(DeviceBatteryStd); DeviceBatteryStd.displayName = 'DeviceBatteryStd'; export default DeviceBatteryStd;
src/svg-icons/navigation/fullscreen-exit.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationFullscreenExit = (props) => ( <SvgIcon {...props}> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/> </SvgIcon> ); NavigationFullscreenExit = pure(NavigationFullscreenExit); NavigationFullscreenExit.displayName = 'NavigationFullscreenExit'; NavigationFullscreenExit.muiName = 'SvgIcon'; export default NavigationFullscreenExit;
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
greatdinosaur/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class UserProfileContactInfo extends React.Component { static propTypes = { phones: React.PropTypes.array }; constructor(props) { super(props); } render() { let phones = this.props.phones; let contactPhones = _.map(phones, (phone, i) => { return ( <li className="profile__list__item row" key={i}> <i className="material-icons">call</i> <div className="col-xs"> <span className="contact">+{phone.number}</span> <span className="title">{phone.title}</span> </div> </li> ); }); return ( <ul className="profile__list profile__list--contacts"> {contactPhones} </ul> ); } } export default UserProfileContactInfo;
examples/forms-bootstrap/src/components/dialogs-create-wizard-generic/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import config from './config'; export default createReactClass({ displayName: 'Hook', render: function() { return ( <div style={{ padding: '20px' }}> <button className="btn btn-primary" onClick={() => { lore.dialog.show(() => ( lore.dialogs.tweet.create(config) )) }} > Open Dialog </button> </div> ); } });
src/components/TextRotator.js
dkozar/react-data-menu
import React, { Component } from 'react'; import WrappyText from 'react-wrappy-text'; const texts = [ 'This menu is data driven (hierarchy is not hardcoded).', 'Open the drop-down menu on top.', 'Check out the bottom menu.', 'Right-click the application background for context menu.', 'Right-click the circle for another context menu.', 'Menu popups are fully customizable. Menu items too.', 'None of the popups should ever be cropped by screen edges.', 'You can specify directions of popups by providing hints.' ]; export default class TextRotator extends Component { constructor(props) { super(props); this.state = { index: 0, text: texts[0] }; this.start(); } start() { this.interval = setInterval( () => { var index = (this.state.index + 1) % texts.length; this.setState({ index, text: texts[index] }); }, 5000 ); } stop() { clearInterval(this.interval); this.interval = null; } render() { return ( <WrappyText className='wrappy'>{this.state.text}</WrappyText> ); } }
app/edit/index.js
hukaibaihu/dogsay
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; export default class Edit extends Component { constructor(props){ super(props) } render() { return ( <View style={styles.container}> <Text>制作页面</Text> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF' } });
client/src/app/app.js
DukeNLIDB/NLIDB
import React, { Component } from 'react'; import styled from 'styled-components'; import Form from '../common/form'; import SearchBar from './components/search-bar'; import buttonStyle from '../styles/button'; const Wrapper = styled.div` max-width: 1200px; margin: auto; `; const Title = styled.h1` text-align: center; `; const ResultText = styled.div` margin: 0 auto; width: 800px; `; const Text = styled.div` text-align: center; margin: 0 5px; `; const Button = styled.button` ${() => buttonStyle} `; const StatusBar = styled.div` display: flex; justify-content: center; align-items: center; `; const VerticalCenterDiv = styled.div` display: flex; flex-direction: column; align-items: center; `; class App extends Component { componentDidMount() { const { connectUserSession } = this.props; connectUserSession(); } render() { const { connected, connectErrorMsg, databaseUrl, translateResult, queryResult, disconnect, connectToDB, connectToDemoDB, translateNL, executeSQL, } = this.props; return ( <Wrapper> <Title>Natural Language Interface to DataBases</Title> { connected ? ( <div> <StatusBar> <Text>connected to {databaseUrl}</Text> <Button onClick={disconnect}>disconnect</Button> </StatusBar> <SearchBar title={'Natural Language Input:'} submit={input => translateNL({ input })} buttonTitle={'translate'} /> <ResultText>{translateResult}</ResultText> <SearchBar title={'SQL Query:'} submit={input => executeSQL({ query: input })} buttonTitle={'execute'} /> <ResultText> <pre>{queryResult}</pre> </ResultText> </div> ) : ( <VerticalCenterDiv> <Button onClick={connectToDemoDB}>connect to demo DB</Button> <Form key={1} message={connectErrorMsg} fields={[ { name: 'host' }, { name: 'port' }, { name: 'database' }, { name: 'username' }, { name: 'password', type: 'password' }, ]} button={{ name: 'connect', submit: connectToDB, }} /> </VerticalCenterDiv> ) } </Wrapper> ); } } export default App;
src/index.js
chrisrzhou/chris-and-monika
import React from 'react'; import {render} from 'react-dom'; import App from './components/app'; render( <App />, document.getElementById('root'), );
src/pages/chart/ECharts/ChartWithEventComponent.js
zuiidea/antd-admin
import React from 'react' import ReactEcharts from 'echarts-for-react' const ChartWithEventComponent = () => { const onChartReady = echart => { /* eslint-disable */ console.log('echart is ready', echart) } const onChartLegendselectchanged = (param, echart) => { console.log(param, echart) } const onChartClick = (param, echart) => { console.log(param, echart) } const getOtion = () => { const option = { title: { text: '某站点用户访问来源', subtext: '纯属虚构', x: 'center', }, tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)', }, legend: { orient: 'vertical', left: 'left', data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎'], }, series: [ { name: '访问来源', type: 'pie', radius: '55%', center: ['50%', '60%'], data: [ { value: 335, name: '直接访问' }, { value: 310, name: '邮件营销' }, { value: 234, name: '联盟广告' }, { value: 135, name: '视频广告' }, { value: 1548, name: '搜索引擎' }, ], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)', }, }, }, ], } return option } let onEvents = { click: onChartClick, legendselectchanged: onChartLegendselectchanged, } let code = 'let onEvents = {\n' + " 'click': onChartClick,\n" + " 'legendselectchanged': onChartLegendselectchanged\n" + '}\n\n' + '<ReactEcharts \n' + ' option={getOtion()} \n' + ' style={{height: 300}} \n' + ' onChartReady={onChartReady} \n' + ' onEvents={onEvents} />' return ( <div className="examples"> <div className="parent"> <label> {' '} Chart With event <strong> onEvents </strong>: (Click the chart, and watch the console) </label> <ReactEcharts option={getOtion()} style={{ height: 300 }} onChartReady={onChartReady} onEvents={onEvents} /> <label> code below: </label> <pre> <code>{code}</code> </pre> </div> </div> ) } export default ChartWithEventComponent
src/helpers/component-config.js
express-labs/pure-react-carousel
/* eslint {'import/no-named-as-default': 0, 'import/no-named-as-default-member': 0} */ import React from 'react'; import ButtonBack from '../ButtonBack/ButtonBack'; import ButtonFirst from '../ButtonFirst/ButtonFirst'; import ButtonLast from '../ButtonLast/ButtonLast'; import ButtonNext from '../ButtonNext/ButtonNext'; import ButtonPlay from '../ButtonPlay/ButtonPlay'; import CarouselProvider from '../CarouselProvider/CarouselProvider'; import Dot from '../Dot/Dot'; import DotGroup from '../DotGroup/DotGroup'; import Image from '../Image/Image'; import ImageWithZoom from '../ImageWithZoom/ImageWithZoom'; import Slide from '../Slide/Slide'; import Slider from '../Slider/Slider'; import Spinner from '../Spinner/Spinner'; import Store from '../Store/Store'; export default { ButtonBack: { component: ButtonBack, props: { children: 'hello', currentSlide: 1, step: 1, carouselStore: new Store({}), totalSlides: 3, visibleSlides: 2, }, }, ButtonFirst: { component: ButtonFirst, props: { children: 'hello', currentSlide: 1, carouselStore: new Store({ currentSlide: 1, totalSlides: 7, visibleSlides: 1, }), totalSlides: 7, }, }, ButtonLast: { component: ButtonLast, props: { children: 'hello', currentSlide: 1, carouselStore: new Store({ currentSlide: 1, totalSlides: 7, visibleSlides: 1, }), totalSlides: 7, visibleSlides: 1, }, }, ButtonNext: { component: ButtonNext, props: { children: 'hello', currentSlide: 1, step: 1, carouselStore: new Store({}), totalSlides: 3, visibleSlides: 2, }, }, ButtonPlay: { component: ButtonPlay, props: { carouselStore: new Store({ isPlaying: false, }), children: <span className="children">Sup?</span>, childrenPause: <span className="play">Play</span>, childrenPlay: <span className="pause">Pause</span>, isPlaying: false, }, }, CarouselProvider: { component: CarouselProvider, props: { children: 'hello', naturalSlideHeight: 125, naturalSlideWidth: 100, totalSlides: 1, }, }, Dot: { component: Dot, props: { children: 'hello', currentSlide: 0, slide: 2, carouselStore: new Store({ currentSlide: 0, totalSlides: 10, visibleSlides: 2, }), totalSlides: 10, visibleSlides: 2, }, }, DotGroup: { component: DotGroup, props: { currentSlide: 1, carouselStore: new Store({}), totalSlides: 3, visibleSlides: 2, }, }, Image: { component: Image, props: { hasMasterSpinner: false, orientation: 'horizontal', src: 'bob.jpg', carouselStore: new Store({}), }, }, ImageWithZoom: { component: ImageWithZoom, props: { carouselStore: new Store({}), src: 'bob.jpg', }, }, Slide: { component: Slide, props: { currentSlide: 1, index: 1, naturalSlideHeight: 400, naturalSlideWidth: 300, orientation: 'horizontal', slideSize: 25, totalSlides: 4, visibleSlides: 2, }, }, Slider: { component: Slider, props: { carouselStore: new Store({ currentSlide: 0, }), children: 'hello', currentSlide: 0, disableAnimation: false, disableKeyboard: false, dragEnabled: true, hasMasterSpinner: false, interval: 5000, infinite: false, isPageScrollLocked: false, isPlaying: false, lockOnWindowScroll: false, masterSpinnerFinished: false, naturalSlideHeight: 100, naturalSlideWidth: 100, orientation: 'horizontal', playDirection: 'forward', slideSize: 50, slideTraySize: 250, step: 2, totalSlides: 5, touchEnabled: true, visibleSlides: 2, }, }, Spinner: { component: Spinner, props: {}, }, };
src/svg-icons/device/battery-alert.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryAlert = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/> </SvgIcon> ); DeviceBatteryAlert = pure(DeviceBatteryAlert); DeviceBatteryAlert.displayName = 'DeviceBatteryAlert'; DeviceBatteryAlert.muiName = 'SvgIcon'; export default DeviceBatteryAlert;
src/components/MultiLine.js
linxlad/tracksy-client
import React from 'react'; export const MultiLine = (text) => { return ( text.split('<br />').map((item, key) => { return <span key={key}>{item.trim()}<br/></span>; }) ); }; export default MultiLine;
entry_types/scrolled/package/src/frontend/AudioPlayer/AudioStructuredData.js
tf/pageflow
import React from 'react'; import {ensureProtocol} from '../utils/urls'; import {formatTimeDuration} from '../utils/iso8601'; import {useEntryMetadata} from '../../entryState'; import {StructuredData} from '../StructuredData'; export function AudioStructuredData({file}) { const entryMedadata = useEntryMetadata(); const data = { '@context': 'http://schema.org', '@type': 'AudioObject', name: file.basename, description: file.configuration.alt, url: ensureProtocol('https', file.urls.mp3), duration: formatTimeDuration(file.durationInMs), datePublished: entryMedadata.publishedAt, uploadDate: file.createdAt, copyrightHolder: { '@type': 'Organization', name: file.rights } }; return ( <StructuredData data={data} /> ); }
modules/gui/src/widget/widget.js
openforis/sepal
import {Layout} from 'widget/layout' import {compose} from 'compose' import Label from 'widget/label' import PropTypes from 'prop-types' import React from 'react' import styles from './widget.module.css' import withForwardedRef from 'ref' export class _Widget extends React.Component { render() { const {forwardedRef, layout, spacing, alignment, framed, border, disabled, className, onMouseOver, onMouseOut, onClick} = this.props const widgetState = this.getWidgetState() return ( <div ref={forwardedRef} className={[ styles.container, styles[widgetState], onClick && !disabled ? styles.clickable : null, disabled ? styles.disabled : null, ['vertical-scrollable', 'vertical-fill'].includes(layout) ? styles.scrollable : null, className ].join(' ')} onClick={e => onClick && onClick(e)}> {this.renderLabel()} <Layout type={layout} alignment={alignment} spacing={spacing} framed={framed} className={[ styles.widget, disabled ? styles.normal : styles[widgetState], border ? styles.border : null ].join(' ')} onMouseOver={onMouseOver} onMouseOut={onMouseOut} > {this.renderContent()} </Layout> </div> ) } renderContent() { const {children} = this.props return children } getWidgetState() { const {errorMessage, busyMessage} = this.props if (errorMessage) return 'error' if (busyMessage) return 'busy' return 'normal' } renderLabel() { const {label, labelButtons, alignment, tooltip, tooltipPlacement, tooltipTrigger, disabled, errorMessage} = this.props return label ? ( <Label msg={label} buttons={labelButtons} alignment={alignment} tooltip={tooltip} tooltipPlacement={tooltipPlacement} tooltipTrigger={tooltipTrigger} tabIndex={-1} error={!disabled && errorMessage} /> ) : null } getBusyMessage() { const {busyMessage} = this.props return busyMessage } } export const Widget = compose( _Widget, withForwardedRef() ) Widget.propTypes = { children: PropTypes.any.isRequired, alignment: PropTypes.any, border: PropTypes.any, busyMessage: PropTypes.any, className: PropTypes.string, disabled: PropTypes.any, errorMessage: PropTypes.any, framed: PropTypes.any, label: PropTypes.any, labelButtons: PropTypes.any, layout: PropTypes.any, spacing: PropTypes.any, tooltip: PropTypes.any, tooltipPlacement: PropTypes.any, tooltipTrigger: PropTypes.any, onClick: PropTypes.func, onMouseOut: PropTypes.func, onMouseOver: PropTypes.func } Widget.defaultProps = { layout: 'vertical', spacing: 'none' // TODO: why spacing none by default? }
client/src/javascript/components/modals/torrent-details-modal/TorrentPeers.js
jfurrow/flood
import {FormattedMessage} from 'react-intl'; import React from 'react'; import Badge from '../../general/Badge'; import Size from '../../general/Size'; import Checkmark from '../../icons/Checkmark'; const checkmark = <Checkmark />; export default class TorrentPeers extends React.Component { constructor() { super(); this.state = { erroredCountryImages: [], }; } flagImageAsErrored(countryCode) { const {erroredCountryImages} = this.state; erroredCountryImages.push(countryCode); this.setState({erroredCountryImages}); } getImageErrorHandlerFn(countryCode) { return () => this.flagImageAsErrored(countryCode); } render() { const {peers} = this.props; if (peers) { const {erroredCountryImages} = this.state; const peerList = peers.map(peer => { const {country: countryCode} = peer; const encryptedIcon = peer.isEncrypted ? checkmark : null; let peerCountry = null; if (countryCode) { let image = null; if (!erroredCountryImages.includes(countryCode)) { let flagImageSrc; try { // We can ignore the lint warnings becuase we need all of the flags available for request. // eslint-disable-next-line global-require,no-undef,import/no-dynamic-require flagImageSrc = require(`../../../../images/flags/${countryCode.toLowerCase()}.png`); } catch (err) { this.flagImageAsErrored(countryCode); flagImageSrc = null; } if (flagImageSrc) { image = ( <img alt={countryCode} className="peers-list__flag__image" onError={this.getImageErrorHandlerFn(countryCode)} src={flagImageSrc} /> ); } } peerCountry = ( <span className="peers-list__flag"> {image} <span className="peers-list__flag__text">{countryCode}</span> </span> ); } return ( <tr key={peer.address}> <td> {peerCountry} {peer.address} </td> <td> <Size value={peer.downloadRate} isSpeed /> </td> <td> <Size value={peer.uploadRate} isSpeed /> </td> <td>{peer.completedPercent}%</td> <td>{peer.clientVersion}</td> <td className="peers-list__encryption">{encryptedIcon}</td> </tr> ); }); return ( <div className="torrent-details__section torrent-details__section--peers"> <table className="torrent-details__table table"> <thead className="torrent-details__table__heading"> <tr> <th className="torrent-details__table__heading--primary"> <FormattedMessage id="torrents.details.peers" defaultMessage="Peers" /> <Badge>{peers.length}</Badge> </th> <th className="torrent-details__table__heading--secondary">DL</th> <th className="torrent-details__table__heading--secondary">UL</th> <th className="torrent-details__table__heading--secondary">%</th> <th className="torrent-details__table__heading--secondary">Client</th> <th className="torrent-details__table__heading--secondary">Enc</th> </tr> </thead> <tbody>{peerList}</tbody> </table> </div> ); } return ( <span className="torrent-details__section__null-data"> <FormattedMessage id="torrents.details.peers.no.data" defaultMessage="There is no peer data for this torrent." /> </span> ); } }
src/routes.js
yomolify/cc_material
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, Home, Results, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Results}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
examples/async/index.js
dsimmons/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
tests/lib/rules/vars-on-top.js
DavidAnson/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/vars-on-top"), { RuleTester } = require("../../../lib/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const ruleTester = new RuleTester(); const error = { messageId: "top", type: "VariableDeclaration" }; ruleTester.run("vars-on-top", rule, { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", { code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "export var x;", "var y;", "var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "var x;", "export var y;", "var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "var x;", "var y;", "export var z;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" } }, { code: [ "class C {", " static {", " var x;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } }, { code: [ "class C {", " static {", " var x;", " foo();", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } }, { code: [ "class C {", " static {", " var x;", " var y;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } }, { code: [ "class C {", " static {", " var x;", " var y;", " foo();", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } }, { code: [ "class C {", " static {", " let x;", " var y;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } }, { code: [ "class C {", " static {", " foo();", " let x;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 } } ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [error] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 6 }, errors: [error] }, { code: "'use strict'; 0; var x; f();", errors: [error] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [error] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [error] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [error] }, { code: [ "export function f() {}", "var x;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [error] }, { code: [ "var x;", "export function f() {}", "var y;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [error] }, { code: [ "import {foo} from 'foo';", "export {foo};", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [error] }, { code: [ "export {foo} from 'foo';", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [error] }, { code: [ "export * from 'foo';", "var test = 1;" ].join("\n"), parserOptions: { ecmaVersion: 6, sourceType: "module" }, errors: [error] }, { code: [ "class C {", " static {", " foo();", " var x;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 }, errors: [error] }, { code: [ "class C {", " static {", " 'use strict';", // static blocks do not have directives " var x;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 }, errors: [error] }, { code: [ "class C {", " static {", " var x;", " foo();", " var y;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 }, errors: [{ ...error, line: 5 }] }, { code: [ "class C {", " static {", " if (foo) {", " var x;", " }", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 }, errors: [error] }, { code: [ "class C {", " static {", " if (foo)", " var x;", " }", "}" ].join("\n"), parserOptions: { ecmaVersion: 2022 }, errors: [error] } ] });
src/components/root.js
polovi/react-baobab
import React from 'react' import {getDisplayName} from '../utils' import PropTypes from '../types' export default function root(tree) { return (Component) => { class ComposedComponent extends React.Component { static displayName = `BaobabRoot(${getDisplayName(Component)})`; static childContextTypes = { tree: PropTypes.baobab } getChildContext() { return {tree}; } render() { return <Component />; } } return ComposedComponent; }; }
admin/src/components/ListColumnsForm.js
lojack/keystone
import classnames from 'classnames'; import React from 'react'; import Transition from 'react-addons-css-transition-group'; var CurrentListStore = require('../stores/CurrentListStore'); var Popout = require('./Popout'); var PopoutList = require('./PopoutList'); var { Button, Checkbox, InputGroup, SegmentedControl } = require('elemental'); var ListColumnsForm = React.createClass({ displayName: 'ListColumnsForm', getInitialState () { return { selectedColumns: {} }; }, getSelectedColumnsFromStore () { var selectedColumns = {}; CurrentListStore.getActiveColumns().forEach(col => { selectedColumns[col.path] = true; }); return selectedColumns; }, togglePopout (visible) { this.setState({ selectedColumns: this.getSelectedColumnsFromStore(), isOpen: visible, }, () => { if (visible) { React.findDOMNode(this.refs.target).focus(); } }); }, toggleColumn (path, value) { let newColumns = this.state.selectedColumns; if (value) { newColumns[path] = value; } else { delete newColumns[path]; } this.setState({ selectedColumns: newColumns }); }, applyColumns () { CurrentListStore.setActiveColumns(Object.keys(this.state.selectedColumns)); this.togglePopout(false); }, renderColumns () { return CurrentListStore.getAvailableColumns().map((el, i) => { if (el.type === 'heading') { return <PopoutList.Heading key={'heading_' + i}>{el.content}</PopoutList.Heading>; } let path = el.field.path; let selected = this.state.selectedColumns[path]; return ( <PopoutList.Item key={'column_' + el.field.path} icon={selected ? 'check' : 'dash'} iconHover={selected ? 'dash' : 'check'} isSelected={!!selected} label={el.field.label} onClick={() => { this.toggleColumn(path, !selected); }} /> ); }); }, render () { return ( <InputGroup.Section className={this.props.className}> <Button ref="target" id="listHeaderColumnButton" isActive={this.state.isOpen} onClick={this.togglePopout.bind(this, !this.state.isOpen)}> <span className={this.props.className + '__icon octicon octicon-list-unordered'} /> <span className={this.props.className + '__label'}>Columns</span> <span className="disclosure-arrow" /> </Button> <Popout isOpen={this.state.isOpen} onCancel={this.togglePopout.bind(this, false)} relativeToID="listHeaderColumnButton"> <Popout.Header title="Columns" /> <Popout.Body scrollable> <PopoutList> {this.renderColumns()} </PopoutList> </Popout.Body> <Popout.Footer primaryButtonAction={this.applyColumns} primaryButtonLabel="Apply" secondaryButtonAction={this.togglePopout.bind(this, false)} secondaryButtonLabel="Cancel" /> </Popout> </InputGroup.Section> ); } }); module.exports = ListColumnsForm;
example/containers/LoggedIn.js
johanneslumpe/redux-history-transitions
import React from 'react'; const LoggedInContainer = () => ( <div> You are logged in, yay! :) </div> ); export default LoggedInContainer;
src/MenuItem.js
sheep902/react-bootstrap
import React from 'react'; import classnames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; import SafeAnchor from './SafeAnchor'; export default class MenuItem extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(event) { if (!this.props.href || this.props.disabled) { event.preventDefault(); } if (this.props.disabled) { return; } if (this.props.onSelect) { this.props.onSelect(event, this.props.eventKey); } } render() { if (this.props.divider) { return <li role="separator" className="divider" />; } if (this.props.header) { return ( <li role="heading" className="dropdown-header">{this.props.children}</li> ); } const classes = { disabled: this.props.disabled, active: this.props.active }; return ( <li role="presentation" className={classnames(this.props.className, classes)} style={this.props.style} > <SafeAnchor role="menuitem" tabIndex="-1" id={this.props.id} target={this.props.target} title={this.props.title} href={this.props.href || ''} onKeyDown={this.props.onKeyDown} onClick={this.handleClick}> {this.props.children} </SafeAnchor> </li> ); } } MenuItem.propTypes = { disabled: React.PropTypes.bool, active: React.PropTypes.bool, divider: CustomPropTypes.all([ React.PropTypes.bool, props => { if (props.divider && props.children) { return new Error('Children will not be rendered for dividers'); } } ]), eventKey: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), header: React.PropTypes.bool, href: React.PropTypes.string, target: React.PropTypes.string, title: React.PropTypes.string, onKeyDown: React.PropTypes.func, onSelect: React.PropTypes.func, id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }; MenuItem.defaultProps = { divider: false, disabled: false, header: false };
packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/compound-assignment/actual.js
claudiopro/babel
import React from 'react'; import Loader from 'loader'; const errorComesHere = () => <Loader className="full-height"/>, thisWorksFine = () => <Loader className="p-y-5"/>;
src/components/video_detail.js
hr2204/react_apps
import React from 'react'; const VideoDetail = ({video}) => { if (!video){ return <div>Loading...</div> } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ) } export default VideoDetail;
stories/MatchingBars.stories.js
nekuno/client
import React from 'react'; import { storiesOf } from '@storybook/react'; import MatchingBars from '../src/js/components/ui/MatchingBars/MatchingBars.js'; storiesOf('MatchingBars', module) .add('condensed', () => ( <MatchingBars similarity={0.15} matching={0.30} condensed={true} /> )) .add('expanded', () => ( <MatchingBars similarity={0.15} matching={0.30} condensed={false} /> ));
src/svg-icons/image/filter-3.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter3 = (props) => ( <SvgIcon {...props}> <path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z"/> </SvgIcon> ); ImageFilter3 = pure(ImageFilter3); ImageFilter3.displayName = 'ImageFilter3'; export default ImageFilter3;
app/components/DateRangeInput/index.js
Ennovar/clock_it
/** * * DateRangeInput * */ import React from 'react'; import styled from 'styled-components'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; const DatePicker = styled.div` margin-bottom: 8px; margin-top: 8px; `; const Picker = styled.input` height: 29px; margin-left: 8px; margin-right: 8px; background: #eee; `; const Controls = styled.div` padding: 8px; `; class DateRangeInput extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <DatePicker> <div> <FormattedMessage {...messages.header} /> </div> <Controls> <strong>From</strong> <Picker onChange={this.props.onFromChanged} type="date" /> <strong>Two</strong> <Picker onChange={this.props.onEndChanged} type="date" /> </Controls> </DatePicker> ); } } DateRangeInput.propTypes = { onFromChanged: React.PropTypes.func, onEndChanged: React.PropTypes.func, }; export default DateRangeInput;
website/src/PageWithSidebar.js
half-shell/react-navigation
import React, { Component } from 'react'; import Link from "./Link"; import { NavigationActions, addNavigationHelpers } from 'react-navigation'; const LinkableLi = Link.Linkable(props => <li {...props} />); function getConfig(router, state, action, configName) { if (action) { state = router.getStateForAction(action, state); } const Component = router.getComponentForState(state); return Component.navigationOptions[configName]; } class PageWithSidebar extends Component { render() { const {router, navigation} = this.props; const {dispatch, state} = navigation; const ActiveScreen = router.getComponentForState(state); let prevAction = null; if (state.routes[state.index].index > 0) { const prev = state.routes[state.index].index - 1; prevAction = NavigationActions.navigate({ routeName: state.routes[state.index].routes[prev].routeName, }); } if (!prevAction && state.index > 0) { const prev = state.index - 1; prevAction = NavigationActions.navigate({ routeName: state.routes[prev].routeName, action: NavigationActions.navigate({ routeName: state.routes[prev].routes[state.routes[prev].routes.length - 1].routeName, }) }); } let nextAction = null; if (state.routes[state.index].index < state.routes[state.index].routes.length - 1) { const next = state.routes[state.index].index + 1; nextAction = NavigationActions.navigate({ routeName: state.routes[state.index].routes[next].routeName, }); } if (!nextAction && state.index < state.routes.length - 1) { const next = state.index + 1; nextAction = NavigationActions.navigate({ routeName: state.routes[next].routeName, }); } let prevName = prevAction && getConfig(router, state, prevAction, 'linkName'); let nextName = nextAction && getConfig(router, state, nextAction, 'linkName'); const docPath = getConfig(router, state, null, 'doc')+'.md'; return ( <div className="page-body"><div className="inner-page-body"> <div className="left-sidebar"> <ul className="pt-menu pt-elevation-1 navmenu"> {state.routes && state.routes.map((route, i) => { const DocComponent = router.getComponentForRouteName(route.routeName); const childNavigation = addNavigationHelpers({ state: route, dispatch, }); const linkName = router.getScreenConfig(childNavigation, 'linkName'); const icon = router.getScreenConfig(childNavigation, 'icon'); const isActive = state.index === i; return ( <span key={i}> <LinkableLi to={route.routeName} className={"pt-menu-header "+icon+' '+(isActive?'active':'')}> <h6>{linkName}</h6> </LinkableLi> <div> {route.routes && route.routes.map((childRoute, childI) => { const isChildActive = isActive && route.index === childI; const secondChildNavigation = addNavigationHelpers({ state: childRoute, dispatch, }); const routerLinkName = DocComponent.router && DocComponent.router.getScreenConfig(secondChildNavigation, 'linkName'); const linkName = routerLinkName || childRoute.routeName; return ( <Link to={childRoute.routeName} className={`pt-menu-item page ${(isChildActive) ? 'active' : ''}`} key={childI}> {linkName} </Link> ); })} </div> </span> ); })} </ul> </div> <div className="main-section"> <ActiveScreen navigation={this.props.navigation} /> <hr /> {state.routeName === 'Docs' && <Link href={`https://github.com/react-community/react-navigation/tree/master/docs/${docPath}`} className="editLink"> Edit on GitHub</Link>} {prevAction && <Link to={prevAction}>Previous: {prevName}</Link>} {nextAction && <Link to={nextAction} className="nextLink">Next: {nextName}</Link>} </div> </div></div> ); } } export default PageWithSidebar;
src/svg-icons/image/details.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageDetails = (props) => ( <SvgIcon {...props}> <path d="M3 4l9 16 9-16H3zm3.38 2h11.25L12 16 6.38 6z"/> </SvgIcon> ); ImageDetails = pure(ImageDetails); ImageDetails.displayName = 'ImageDetails'; export default ImageDetails;
libs/pureComponent/index.js
eleme/element-react
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export default class PureComponent extends React.PureComponent { classNames(...args) { return classnames(args); } className(...args) { const { className } = this.props; return this.classNames.apply(this, args.concat([className])); } style(args) { const { style } = this.props; return Object.assign({}, args, style) } } PureComponent.propTypes = { className: PropTypes.string, style: PropTypes.object };
src/svg-icons/image/crop-rotate.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropRotate = (props) => ( <SvgIcon {...props}> <path d="M7.47 21.49C4.2 19.93 1.86 16.76 1.5 13H0c.51 6.16 5.66 11 11.95 11 .23 0 .44-.02.66-.03L8.8 20.15l-1.33 1.34zM12.05 0c-.23 0-.44.02-.66.04l3.81 3.81 1.33-1.33C19.8 4.07 22.14 7.24 22.5 11H24c-.51-6.16-5.66-11-11.95-11zM16 14h2V8c0-1.11-.9-2-2-2h-6v2h6v6zm-8 2V4H6v2H4v2h2v8c0 1.1.89 2 2 2h8v2h2v-2h2v-2H8z"/> </SvgIcon> ); ImageCropRotate = pure(ImageCropRotate); ImageCropRotate.displayName = 'ImageCropRotate'; ImageCropRotate.muiName = 'SvgIcon'; export default ImageCropRotate;
src/app.js
jonatassaraiva/learn-react-native-manager
import React, { Component } from 'react'; import { View } from 'react-native'; import { Provider } from 'react-redux'; import firebase from 'firebase'; import { firebaseSetting } from '../settings'; import store from './store'; import Router from './router'; class App extends Component { constructor(props) { super(props); } componentWillMount() { this.store = store.configure(); firebase.initializeApp(firebaseSetting); } render() { return ( <Provider store={this.store}> <View style={{ flex: 1 }}> <Router /> </View> </Provider> ); } } export default App;
src/components/Header/Header.js
blackshade91/daf-dataportal
import React, { Component } from 'react'; import { Dropdown, DropdownMenu, DropdownItem } from 'reactstrap'; import PropTypes from 'prop-types' import { Redirect } from 'react-router' import { Link } from 'react-router-dom'; import { connect } from 'react-redux' import { loadDatasets, unloadDatasets, datasetDetail, logout } from '../../actions' import { createBrowserHistory } from 'history'; import AutocompleteDataset from '../Autocomplete/AutocompleteDataset.js' const history = createBrowserHistory(); class Header extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleLoadDatasetClick = this.handleLoadDatasetClick.bind(this); this.toggle = this.toggle.bind(this); this.state = { dropdownOpen: false, value: '' }; } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } sidebarToggle(e) { e.preventDefault(); document.body.classList.toggle('sidebar-hidden'); } sidebarMinimize(e) { e.preventDefault(); document.body.classList.toggle('sidebar-minimized'); } mobileSidebarToggle(e) { e.preventDefault(); document.body.classList.toggle('sidebar-mobile-show'); } asideToggle(e) { e.preventDefault(); document.body.classList.toggle('aside-menu-hidden'); } handleChange(event) { this.setState({value: event.target.value}); } handleLoadDatasetClick(event) { console.log('Serach Dataset for: ' + this.refs.auto.state.value); event.preventDefault(); const { dispatch, selectDataset } = this.props; dispatch(loadDatasets(this.refs.auto.state.value)); this.props.history.push('/dataset'); } render() { const { loggedUser } = this.props return ( <header className="app-header navbar"> <button className="navbar-toggler mobile-sidebar-toggler d-lg-none" onClick={this.mobileSidebarToggle} type="button">&#9776;</button> <button className="nav-link navbar-toggler sidebar-toggler" type="button" onClick={this.sidebarToggle}>&#9776;</button> <ul className="nav navbar-nav d-md-down-none mr-auto"> <li className="nav-item brand"> <a href=""><span>DAF </span></a> </li> </ul> <ul className="nav navbar-nav d-md-down-none"> <AutocompleteDataset ref="auto"/> <button className="btn btn-default" type="submit" value="submit" onClick={this.handleLoadDatasetClick}>Cerca</button> </ul> <ul className="nav navbar-nav ml-auto"> <li className="nav-item"> <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> <button onClick={this.toggle} className="nav-link dropdown-toggle" data-toggle="dropdown" type="button" aria-haspopup="true" aria-expanded={this.state.dropdownOpen}> <img src={'img/avatars/7.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="d-md-down-none">{loggedUser?loggedUser.name:''}</span> </button> <DropdownMenu className="dropdown-menu-right"> <DropdownItem header className="text-center"><strong>Menu utente</strong></DropdownItem> <DropdownItem><a className="nav-link" href="/#/profile"><i className="fa fa-user"></i> Profilo</a></DropdownItem> <DropdownItem> <a className="nav-link" onClick={() => { logout() }} href="/"><i className="fa fa-lock"></i> Logut</a></DropdownItem> </DropdownMenu> </Dropdown> </li> <li className="nav-item hidden-md-down"> <a className="nav-link navbar-toggler aside-menu-toggler" href="#"></a> </li> </ul> </header> ) } } /* <header className="app-header navbar"> <button className="navbar-toggler mobile-sidebar-toggler d-lg-none" onClick={this.mobileSidebarToggle} type="button">&#9776;</button> <a className="navbar-brand" href="#"></a> <ul className="nav navbar-nav d-md-down-none mr-auto"> <li className="nav-item"> <button className="nav-link navbar-toggler sidebar-toggler" type="button" onClick={this.sidebarToggle}>&#9776;</button> </li> </ul> <ul className="nav navbar-nav d-md-down-none"> <AutocompleteDataset ref="auto"/> <button className="btn btn-outline-success my-2 my-sm-0" type="submit" value="submit" onClick={this.handleLoadDatasetClick}>Cerca</button> </ul> <ul className="nav navbar-nav ml-auto"> <li className="nav-item"> <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> <button onClick={this.toggle} className="nav-link dropdown-toggle" data-toggle="dropdown" type="button" aria-haspopup="true" aria-expanded={this.state.dropdownOpen}> <img src={'img/avatars/7.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="d-md-down-none">{loggedUser?loggedUser.email:''}</span> </button> <DropdownMenu className="dropdown-menu-right"> <DropdownItem header className="text-center"><strong>Settings</strong></DropdownItem> <DropdownItem><a className="nav-link" href="/#/profile"><i className="fa fa-user"></i> Profile</a></DropdownItem> <DropdownItem><i className="fa fa-wrench"></i> Settings</DropdownItem> <DropdownItem divider /> <DropdownItem> <a className="nav-link" onClick={() => { logout() }} href="/"><i className="fa fa-lock"></i> Logut</a></DropdownItem> </DropdownMenu> </Dropdown> </li> <li className="nav-item hidden-md-down"> <a className="nav-link navbar-toggler aside-menu-toggler" href="#"></a> </li> </ul> </header> */ /* <form className="form-inline my-2 my-lg-0" onSubmit={this.handleSubmit}> <input className="form-control mr-sm-2" type="text" placeholder="Cerca Dataset" value={this.state.value} onChange={this.handleChange}/> <button className="btn btn-outline-success my-2 my-sm-0" type="submit" value="submit">Cerca</button> </form> */ Header.propTypes = { loggedUser: PropTypes.object, value: PropTypes.string } function mapStateToProps(state) { const { loggedUser } = state.userReducer['obj'] || { } return { loggedUser } } export default connect(mapStateToProps)(Header)
pages/about.js
cable729/react-blog
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>About Us</h1> <p>Coming soon.</p> </div> ); } }
src/components/ActivityListMembers/ActivityListMembersKick.js
nolawi/champs-dialog-sg
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import React from 'react'; import { Text } from '@dlghq/react-l10n'; import Spinner from '../Spinner/Spinner'; import Tooltip from '../Tooltip/Tooltip'; import Icon from '../Icon/Icon'; import styles from './ActivityListMembers.css'; import errorToString from '../../utils/errorToString'; export type Props = { error: ?(Error | string), pending: boolean, onClick: (event: SyntheticMouseEvent) => void }; function ActivityListMembersKick(props: Props) { if (props.pending) { return ( <Spinner type="round" className={styles.kickMemberPending} /> ); } const error = errorToString(props.error); if (error) { return ( <Tooltip text={error} options={{ attachment: 'middle right', targetAttachment: 'middle left', constraints: [ { to: 'window', attachment: 'together' } ] }} > <Icon glyph="error" className={styles.kickMemberError} onClick={props.onClick} /> </Tooltip> ); } return ( <div className={styles.kickMember} onClick={props.onClick}> <Text id="ActivityListMembers.kick" /> </div> ); } export default ActivityListMembersKick;
src/js/components/ui/PasswordInput.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import shouldPureComponentUpdate from 'react-pure-render/function'; export default class PasswordInput extends Component { static propTypes = { placeholder: PropTypes.string.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; getValue() { return this.refs.input.value; } render() { return ( <li> <div className="item-content"> <div className="item-inner"> <div className="item-input"> <input {...this.props} ref="input" type="password" placeholder={this.props.placeholder}/> </div> </div> </div> </li> ); } }
src/modules/referenceWorks/components/ReferenceWorkDetail/ReferenceWorkDetail.js
CtrHellenicStudies/Commentary
import React from 'react'; import PropTypes from 'prop-types'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; // components import BackgroundImageHolder from '../../../shared/components/BackgroundImageHolder'; import CommentsRecent from '../../../comments/components/CommentsRecent'; import Header from '../../../../components/navigation/Header'; // lib import muiTheme from '../../../../lib/muiTheme'; const createMarkup = (referenceWork) => { let __html = ''; __html += '<p>'; if (referenceWork.desc) { __html += referenceWork.desc.replace('\n', '</p><p>'); } else { __html += 'No description is available for this work.'; } __html += '</p>'; return { __html, }; } const ReferenceWorkDetail = ({ referenceWork, settings, commenters }) => ( <MuiThemeProvider muiTheme={getMuiTheme(muiTheme)}> <div className="page reference-works-page reference-works-detail-page"> <Header /> <div className="content primary"> <section className="block header header-page cover parallax"> <BackgroundImageHolder imgSrc="/images/apotheosis_homer.jpg" /> <div className="container v-align-transform"> <div className="grid inner"> <div className="center-content"> <div className="page-title-wrap"> <h2 className="page-title ">{referenceWork.title}</h2> {referenceWork.link ? <a className="read-online-link" href={referenceWork.link} target="_blank" rel="noopener noreferrer" > Read Online <i className="mdi mdi-open-in-new" /> </a> : ''} </div> </div> </div> </div> </section> <section className="page-content"> {commenters && commenters.length ? <div className="page-byline"> <h3>By {commenters.map((commenter, i) => { let ending = ''; if (i < commenters.length - 2) { ending = ', '; } else if (i < commenters.length - 1) { ending = ' and '; } return ( <span key={i} > <a href={`/commenters/${commenter.slug}`} > {commenter.name} </a>{ending} </span> ); })} </h3> </div> : ''} <div dangerouslySetInnerHTML={createMarkup(referenceWork)} /> </section> <CommentsRecent /> </div> </div> </MuiThemeProvider> ); ReferenceWorkDetail.propTypes = { referenceWorks: PropTypes.object, settings: PropTypes.object, }; export default ReferenceWorkDetail;
src/svg-icons/maps/map.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsMap = (props) => ( <SvgIcon {...props}> <path d="M20.5 3l-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"/> </SvgIcon> ); MapsMap = pure(MapsMap); MapsMap.displayName = 'MapsMap'; export default MapsMap;
node_modules/react-icons/io/lock-combination.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoLockCombination = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m30 13.8c3 2.8 5 6.7 5 11.2 0 8.3-6.7 15-15 15s-15-6.7-15-15c0-4.5 2-8.4 5-11.2v-3.8c0-5.5 4.5-10 10-10s10 4.5 10 10v3.8z m-17.5-3.8v2c2.2-1.2 4.8-2 7.5-2s5.3 0.8 7.5 2v-2c0-4.1-3.4-7.5-7.5-7.5s-7.5 3.4-7.5 7.5z m7.5 27.5c6.9 0 12.5-5.6 12.5-12.5s-5.6-12.5-12.5-12.5-12.5 5.6-12.5 12.5 5.6 12.5 12.5 12.5z m0-23.7c6.3 0 11.3 5 11.3 11.2s-5 11.3-11.3 11.3-11.2-5-11.2-11.3 5-11.2 11.2-11.2z m9.6 13.8c0.2-0.7 0.3-1.4 0.3-2.3h-0.5v-0.5h0.6c0-0.9-0.2-1.6-0.4-2.4l-1.9 0.6-0.4-1 2-0.6c-0.3-0.8-0.6-1.4-1.1-2l-0.9 0.6-0.3-0.5 0.9-0.6c-0.5-0.6-1-1.2-1.7-1.7l-1.1 1.6-0.9-0.6 1.2-1.6c-0.6-0.4-1.3-0.8-2.1-1.1l-0.3 1.1-0.5-0.2 0.4-1c-0.7-0.2-1.6-0.4-2.3-0.4v1.5h-1.2v-1.5c-0.9 0.1-1.5 0.2-2.3 0.4l0.3 0.9-0.5 0.2-0.3-1c-0.7 0.3-1.4 0.7-2.1 1.1l1.2 1.6-0.8 0.6-1.2-1.6c-0.6 0.5-1.2 1.1-1.7 1.7l0.9 0.6-0.3 0.4-0.8-0.6c-0.5 0.6-0.8 1.3-1.1 2.1l1.9 0.6-0.4 1-2-0.6c-0.2 0.8-0.2 1.5-0.2 2.4h0.5v0.5h-0.4c0 0.9 0.1 1.6 0.3 2.3l1.9-0.6 0.3 1-1.9 0.6c0.3 0.8 0.6 1.5 1.1 2.1l0.7-0.5 0.3 0.3-0.7 0.6c0.5 0.6 1 1.2 1.6 1.7l1.2-1.6 0.8 0.6-1.2 1.6c0.7 0.4 1.4 0.8 2.1 1.1l0.3-0.9 0.5 0.2-0.3 0.8c0.8 0.2 1.4 0.3 2.3 0.4v-1.5h1.2v1.5c0.7-0.1 1.5-0.2 2.3-0.4l-0.4-0.9 0.5-0.2 0.3 1c0.8-0.3 1.5-0.7 2.1-1.1l-1.2-1.6 0.9-0.6 1.1 1.6c0.7-0.5 1.2-1.1 1.7-1.7l-0.9-0.6 0.3-0.4 0.8 0.6c0.5-0.6 0.9-1.3 1.2-2.1l-2-0.6 0.4-1z m-15.9-2.6c0-4.2 2.1-6.3 6.3-6.3s6.3 2.1 6.3 6.3-2.1 6.3-6.3 6.3-6.3-2.1-6.3-6.3z"/></g> </Icon> ) export default IoLockCombination
src/js/components/FileInput/stories/CustomThemed/Custom.js
HewlettPackard/grommet
import React from 'react'; import { Box, Grommet, FileInput, Text } from 'grommet'; import { Trash } from 'grommet-icons'; const customTheme = { fileInput: { button: { hover: { color: 'accent-2', }, border: { color: 'skyblue', width: '1px', }, pad: { vertical: '4px', horizontal: '8px', }, }, message: { color: 'green', textAlign: 'center', }, background: '#f2f2f2', border: { size: 'medium' }, pad: { horizontal: 'large', vertical: 'medium' }, round: 'small', label: { size: 'large', }, icons: { remove: Trash, }, dragOver: { border: { color: 'focus' }, }, hover: { border: { color: 'control' }, extend: `letterSpacing: '0.1em'`, }, }, }; export const Custom = () => ( <Grommet full theme={customTheme}> <Box fill align="center" justify="start" pad="large"> <Box width="medium"> <FileInput renderFile={(file) => ( <Box direction="row" gap="small"> <Text weight="bold">{file.name}</Text> <Text color="text-weak">{file.size} bytes</Text> </Box> )} multiple={{ max: 5, }} messages={{ maxFile: 'You can only select a maximum of 5 files.', }} onChange={(event, { files }) => { const fileList = files; for (let i = 0; i < fileList.length; i += 1) { const file = fileList[i]; console.log(file.name); } }} /> </Box> </Box> </Grommet> ); export default { title: 'Input/FileInput/Custom Themed/Custom', };
packages/lore-react-forms-bootstrap/src/fields/select.js
lore/lore-forms
import React from 'react'; import _ from 'lodash'; import { Field } from 'lore-react-forms'; import { Connect } from 'lore-hook-connect'; export default function(form, props, name) { const { options, label, optionLabel, description, ...other } = props; return ( <Field name={name}> {(field) => { const errorText = field.touched && field.error; return ( <div className={`form-group ${errorText ? 'has-error' : ''}`}> <label> {label} </label> <Connect callback={(getState, props) => { return { options: _.isFunction(options) ? options(getState, props) : options }; }}> {(connect) => { return ( <select className="form-control" value={field.value || ''} onChange={(event) => { const value = event.target.value; field.onBlur(); field.onChange(field.name, value ? Number(value) : value); }} style={{ width: '100%' }} {...other} > {[<option key="" value=""/>].concat(connect.options.data.map((datum) => { return ( <option key={datum.id} value={datum.id}> {_.isFunction(optionLabel) ? optionLabel(datum) : datum.data[optionLabel]} </option> ); }))} </select> ) }} </Connect> {errorText ? ( <span className="help-block"> {errorText} </span> ) : null} {description ? ( <span className="help-block"> {description} </span> ) : null} </div> ) }} </Field> ) }
src/components/custom-components/MusicList/MusicList.js
ArtyomVolkov/music-search
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; // actions import * as playerAction from '../../../actions/player'; import * as system from '../../../actions/system'; // Components import ArtistList from '../ArtistList/ArtistList'; import TrackList from '../TrackList/TrackList'; import GenresSection from '../GenresSection/GenresSection'; // Services import RouterService from '../../../services/RouterService/RouterService'; // Style import './MusicList.scss'; @connect( state => ({ searchResults: state.searchResults, player: state.player }), dispatch => ({ playerActions: bindActionCreators(playerAction, dispatch) }) ) class MusicList extends Component { constructor (props) { super(props); } onCallAction = (name, song) => { const { playerActions, player } = this.props; if (name === 'selectSong') { if (player.playList) { // reset playList Data playerActions.setPlayListData(null); } RouterService.navigate(`/artist/${song.stringId}`); } }; onAction = (actionName, track, index) => { if (actionName === 'on-play') { this.onPlaySong(track, index); } }; onPlaySong (track, index) { const { playerActions, player } = this.props; if (player.songData && player.songData.mbid === track.mbid) { if (player.songData.mbid === player.trackIdError) { system.onPushMessage({ type: 'error', msg: 'Error in audio stream' }); return; } // toggle play playerActions.onTogglePlay(); return; } playerActions.playNext(index, 'track'); } render () { const { searchResults, songData } = this.props; return ( <div className="music-list"> { searchResults.type === 'ARTIST' && (searchResults.data && <ArtistList artists={searchResults.data} songData={songData} onAction={this.onCallAction} /> ) } { searchResults.type === 'TRACK' && (searchResults.data && <TrackList type={'track'} tracks={searchResults.data} subHeader={`Found tracks (${searchResults.data.length})`} showActions={true} onAction={this.onAction} /> ) } { searchResults.type === 'GENRE' && (searchResults.data && <GenresSection genres={searchResults.data}/> ) } </div> ); } } export default MusicList;
spec/components/navigation.js
VACO-GitHub/vaco-components-library
import React from 'react'; import Navigation from '../../components/navigation'; import Link from '../../components/link'; const actions = [ { label: 'Alarm', raised: true, icon: 'access_alarm'}, { label: 'Location', raised: true, accent: true, icon: 'room'} ]; const NavigationTest = () => ( <section> <h5>Navigation</h5> <p>lorem ipsum...</p> <Navigation type='horizontal' actions={actions} /> <Navigation type='vertical'> <Link href='http://' label='Inbox' icon='inbox' /> <Link href='http://' active label='Profile' icon='person' /> </Navigation> </section> ); export default NavigationTest;
public/js/components/profile/visitor/activityfeed/activitySharedList.react.js
rajikaimal/Coupley
import React from 'react'; import Card from 'material-ui/lib/card/card'; import CardMedia from 'material-ui/lib/card/card-media'; import CardText from 'material-ui/lib/card/card-text'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; const style1 = { width: 700, margin: 40, }; const ActivitySharedList = React.createClass({ render: function () { return ( <div style={style1}> <div> <Card> <ListItem leftAvatar={<Avatar src="https://s-media-cache-ak0.pinimg.com/236x/dc/15/f2/dc15f28faef36bc55e64560d000e871c.jpg" />} primaryText={this.props.sfirstname} secondaryText={ <p> <b>{this.props.screated_at}</b> </p> } secondaryTextLines={1} /> <CardText> {this.props.spost_text} </CardText> <div> { (this.props.sattachment!='None') ? <div> <CardMedia> <img src={'img/activityFeedPics/'+ this.props.sattachment} /> </CardMedia> </div> : '' } </div> <Divider inset={true} /> </Card> </div> </div> ); } }); export default ActivitySharedList;
src/js/index.js
damianjaniszewski/iot-dashboard
import 'whatwg-fetch'; import { polyfill as promisePolyfill } from 'es6-promise'; import React from 'react'; import ReactDOM from 'react-dom'; import '../scss/index.scss'; import App from './App'; promisePolyfill(); const element = document.getElementById('content'); ReactDOM.render(<App />, element); document.body.classList.remove('loading');
examples/files/core_components/scrollview.js
dabbott/react-native-express
import React from 'react' import { ScrollView, StyleSheet, View } from 'react-native' export default function App() { return ( <ScrollView style={styles.container}> <View style={styles.large} /> <ScrollView horizontal> <View style={styles.small} /> <View style={styles.small} /> <View style={styles.small} /> </ScrollView> <View style={styles.large} /> <View style={styles.small} /> <View style={styles.large} /> </ScrollView> ) } const styles = StyleSheet.create({ container: { flex: 1, }, small: { width: 200, height: 200, marginBottom: 10, marginRight: 10, backgroundColor: 'skyblue', }, large: { width: 300, height: 300, marginBottom: 10, marginRight: 10, backgroundColor: 'steelblue', }, })
.storybook/style/storybook-info.styles.js
Sage/carbon
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const StoryHeader = styled.h1` border-bottom: 1px solid #E6EBED; font-size: 24px; margin: 24px 0px; padding: 0px 0px 5px; `; const StoryCode = styled.code` background-color: #EBEFF0; display: ${props => (props.block ? 'block' : 'inline')}; padding: ${props => (props.padded ? '8px' : '0')}; `; const StyledPre = styled.pre` background-color: #EBEFF0; padding: 32px; `; const StoryCodeBlock = ({ children }) => ( <StyledPre> {Array.isArray(children) ? children.map((item, index) => ( <StoryCode block key={index}> {item} </StoryCode> )) : children} </StyledPre> ); StoryCodeBlock.propTypes = { children: PropTypes.node }; export { StoryHeader, StoryCode, StoryCodeBlock };
webpack/scenes/ContentViews/Table/tableDataGenerator.js
snagoor/katello
import React from 'react'; import { fitContent, expandable, sortable } from '@patternfly/react-table'; import { Link } from 'react-router-dom'; import { urlBuilder } from 'foremanReact/common/urlHelpers'; import { translate as __ } from 'foremanReact/common/I18n'; import LongDateTime from 'foremanReact/components/common/dates/LongDateTime'; import ContentViewIcon from '../components/ContentViewIcon'; import DetailsExpansion from '../expansions/DetailsExpansion'; import ContentViewVersionCell from './ContentViewVersionCell'; import InactiveText from '../components/InactiveText'; import LastSync from '../Details/Repositories/LastSync'; export const buildColumns = () => [ { title: __('Type'), cellFormatters: [expandable], transforms: [fitContent] }, { title: __('Name'), transforms: [sortable], }, __('Last published'), __('Last task'), __('Latest version'), ]; const buildRow = (contentView) => { /* eslint-disable max-len */ const { id, composite, name, last_published: lastPublished, latest_version: latestVersion, latest_version_id: latestVersionId, latest_version_environments: latestVersionEnvironments, last_task: lastTask, } = contentView; /* eslint-enable max-len */ const { last_sync_words: lastSyncWords, started_at: startedAt } = lastTask || {}; const row = [ { title: <ContentViewIcon composite={composite ? true : undefined} /> }, { title: <Link to={`${urlBuilder('content_views', '')}${id}`}>{name}</Link> }, { title: lastPublished ? <LongDateTime date={lastPublished} showRelativeTimeTooltip /> : <InactiveText text={__('Not yet published')} /> }, { title: <LastSync startedAt={startedAt} lastSync={lastTask} lastSyncWords={lastSyncWords} emptyMessage="N/A" /> }, { title: latestVersion ? <ContentViewVersionCell {...{ id, latestVersion, latestVersionId, latestVersionEnvironments, }} /> : <InactiveText style={{ marginTop: '0.5em', marginBottom: '0.5em' }} text={__('Not yet published')} />, }, ]; return row; }; const buildExpandableRows = (contentViews) => { const rows = []; let cvCount = 0; contentViews.forEach((contentView) => { const { id, name, composite, next_version: nextVersion, version_count: versionCount, description, activation_keys: activationKeys, hosts, latest_version_environments: latestVersionEnvironments, latest_version_id: latestVersionId, latest_version: latestVersionName, environments, versions, permissions, generated_for: generatedFor, related_cv_count: relatedCVCount, related_composite_cvs: relatedCompositeCVs, } = contentView; const cells = buildRow(contentView); const cellParent = { cvId: id, cvName: name, cvVersionCount: versionCount, cvComposite: composite, cvNextVersion: nextVersion, latestVersionEnvironments, latestVersionId, latestVersionName, environments, versions, permissions, generatedFor, isOpen: false, cells, }; rows.push(cellParent); const cellChild = { parent: cvCount, cells: [ { title: <DetailsExpansion cvId={id} cvName={name} cvComposite={composite} {...{ activationKeys, hosts, relatedCVCount, relatedCompositeCVs, }} />, props: { colSpan: 2, }, }, { title: description || <InactiveText text={__('No description')} />, props: { colSpan: 4, }, }, ], }; rows.push(cellChild); cvCount = rows.length; }); return { rows }; }; const tableDataGenerator = (results) => { const contentViews = results || []; const columns = buildColumns(); const newRowMappingIds = []; const { rows } = buildExpandableRows(contentViews); rows.forEach(row => row.cvId && newRowMappingIds.push(row.cvId)); return { newRowMappingIds, rows, columns }; }; export default tableDataGenerator;
src/svg-icons/image/leak-add.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLeakAdd = (props) => ( <SvgIcon {...props}> <path d="M6 3H3v3c1.66 0 3-1.34 3-3zm8 0h-2c0 4.97-4.03 9-9 9v2c6.08 0 11-4.93 11-11zm-4 0H8c0 2.76-2.24 5-5 5v2c3.87 0 7-3.13 7-7zm0 18h2c0-4.97 4.03-9 9-9v-2c-6.07 0-11 4.93-11 11zm8 0h3v-3c-1.66 0-3 1.34-3 3zm-4 0h2c0-2.76 2.24-5 5-5v-2c-3.87 0-7 3.13-7 7z"/> </SvgIcon> ); ImageLeakAdd = pure(ImageLeakAdd); ImageLeakAdd.displayName = 'ImageLeakAdd'; ImageLeakAdd.muiName = 'SvgIcon'; export default ImageLeakAdd;
src/index.js
amoghesturi/react-news-app
// Application entrypoint. // Load up the application styles require('../styles/application.scss'); // Render the top-level React component import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render(<App />, document.getElementById('root'));
server/middleware/uniRouter.js
osenvosem/react-mobx-boilerplate
import path from 'path'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import routes from '../../app/routes'; import { config } from '../../package.json'; // javascript links const jsLinks = [ path.join(config.assetsPublicPath, 'vendor.bundle.js'), path.join(config.assetsPublicPath, 'main.bundle.js'), ]; // css links const cssLinks = [ path.join(config.assetsPublicPath, 'styles.bundle.css'), "https://fonts.googleapis.com/css?family=Ubuntu:400,300italic,300,400italic,500,500italic,700,700italic" ]; export default function uniRouter(req, res) { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message) } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps) { res.render('index', { jsLinks, cssLinks, reactRoot: renderToString(<RouterContext {...renderProps} />) }); } else { res.status(404).send('Not found') } }) }
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
KnzkDev/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components'; import Overlay from 'react-overlays/lib/Overlay'; import classNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import detectPassiveEvents from 'detect-passive-events'; import { buildCustomEmojis } from '../../emoji/emoji'; const messages = defineMessages({ emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' }, emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' }, emoji_not_found: { id: 'emoji_button.not_found', defaultMessage: 'No emojos!! (╯°□°)╯︵ ┻━┻' }, custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' }, recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' }, search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' }, people: { id: 'emoji_button.people', defaultMessage: 'People' }, nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' }, food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' }, activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' }, travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' }, objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' }, symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' }, flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' }, }); const assetHost = process.env.CDN_HOST || ''; let EmojiPicker, Emoji; // load asynchronously const backgroundImageFn = () => `${assetHost}/emoji/sheet_10.png`; const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; const categoriesSort = [ 'recent', 'custom', 'people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols', 'flags', ]; class ModifierPickerMenu extends React.PureComponent { static propTypes = { active: PropTypes.bool, onSelect: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; handleClick = e => { this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1); } componentWillReceiveProps (nextProps) { if (nextProps.active) { this.attachListeners(); } else { this.removeListeners(); } } componentWillUnmount () { this.removeListeners(); } handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } attachListeners () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } removeListeners () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } render () { const { active } = this.props; return ( <div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}> <button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button> </div> ); } } class ModifierPicker extends React.PureComponent { static propTypes = { active: PropTypes.bool, modifier: PropTypes.number, onChange: PropTypes.func, onClose: PropTypes.func, onOpen: PropTypes.func, }; handleClick = () => { if (this.props.active) { this.props.onClose(); } else { this.props.onOpen(); } } handleSelect = modifier => { this.props.onChange(modifier); this.props.onClose(); } render () { const { active, modifier } = this.props; return ( <div className='emoji-picker-dropdown__modifiers'> <Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} /> <ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} /> </div> ); } } @injectIntl class EmojiPickerMenu extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), loading: PropTypes.bool, onClose: PropTypes.func.isRequired, onPick: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, intl: PropTypes.object.isRequired, skinTone: PropTypes.number.isRequired, onSkinTone: PropTypes.func.isRequired, }; static defaultProps = { style: {}, loading: true, frequentlyUsedEmojis: [], }; state = { modifierOpen: false, placement: null, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } getI18n = () => { const { intl } = this.props; return { search: intl.formatMessage(messages.emoji_search), notfound: intl.formatMessage(messages.emoji_not_found), categories: { search: intl.formatMessage(messages.search_results), recent: intl.formatMessage(messages.recent), people: intl.formatMessage(messages.people), nature: intl.formatMessage(messages.nature), foods: intl.formatMessage(messages.food), activity: intl.formatMessage(messages.activity), places: intl.formatMessage(messages.travel), objects: intl.formatMessage(messages.objects), symbols: intl.formatMessage(messages.symbols), flags: intl.formatMessage(messages.flags), custom: intl.formatMessage(messages.custom), }, }; } handleClick = emoji => { if (!emoji.native) { emoji.native = emoji.colons; } this.props.onClose(); this.props.onPick(emoji); } handleModifierOpen = () => { this.setState({ modifierOpen: true }); } handleModifierClose = () => { this.setState({ modifierOpen: false }); } handleModifierChange = modifier => { this.props.onSkinTone(modifier); } render () { const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props; if (loading) { return <div style={{ width: 299 }} />; } const title = intl.formatMessage(messages.emoji); const { modifierOpen } = this.state; return ( <div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}> <EmojiPicker perLine={8} emojiSize={22} sheetSize={32} custom={buildCustomEmojis(custom_emojis)} color='' emoji='' set='twitter' title={title} i18n={this.getI18n()} onClick={this.handleClick} include={categoriesSort} recent={frequentlyUsedEmojis} skin={skinTone} showPreview={false} backgroundImageFn={backgroundImageFn} autoFocus emojiTooltip /> <ModifierPicker active={modifierOpen} modifier={skinTone} onOpen={this.handleModifierOpen} onClose={this.handleModifierClose} onChange={this.handleModifierChange} /> </div> ); } } export default @injectIntl class EmojiPickerDropdown extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), intl: PropTypes.object.isRequired, onPickEmoji: PropTypes.func.isRequired, onSkinTone: PropTypes.func.isRequired, skinTone: PropTypes.number.isRequired, }; state = { active: false, loading: false, }; setRef = (c) => { this.dropdown = c; } onShowDropdown = ({ target }) => { this.setState({ active: true }); if (!EmojiPicker) { this.setState({ loading: true }); EmojiPickerAsync().then(EmojiMart => { EmojiPicker = EmojiMart.Picker; Emoji = EmojiMart.Emoji; this.setState({ loading: false }); }).catch(() => { this.setState({ loading: false }); }); } const { top } = target.getBoundingClientRect(); this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); } onHideDropdown = () => { this.setState({ active: false }); } onToggle = (e) => { if (!this.state.loading && (!e.key || e.key === 'Enter')) { if (this.state.active) { this.onHideDropdown(); } else { this.onShowDropdown(e); } } } handleKeyDown = e => { if (e.key === 'Escape') { this.onHideDropdown(); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } render () { const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis } = this.props; const title = intl.formatMessage(messages.emoji); const { active, loading, placement } = this.state; return ( <div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}> <div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}> <img className={classNames('emojione', { 'pulse-loading': active && loading })} alt='🙂' src={`${assetHost}/emoji/1f602.svg`} /> </div> <Overlay show={active} placement={placement} target={this.findTarget}> <EmojiPickerMenu custom_emojis={this.props.custom_emojis} loading={loading} onClose={this.onHideDropdown} onPick={onPickEmoji} onSkinTone={onSkinTone} skinTone={skinTone} frequentlyUsedEmojis={frequentlyUsedEmojis} /> </Overlay> </div> ); } }
src/ContentBlocks/Shared/VideoPlayer/ProgressBar.js
grommet/grommet-cms-content-blocks
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Box from 'grommet/components/Box'; import CSSClassnames from 'grommet/utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.VIDEO; export default class ProgressBar extends Component { constructor () { super(); this._onProgressBarChange = this._onProgressBarChange.bind(this); } // prevents unnecessarily updates/re-renders shouldComponentUpdate (nextProps) { return this.props.progress !== nextProps.progress; } _onProgressBarChange (e) { this.props.onChange(e.target.value * this.props.duration / 100); } _onChapterClick (time) { this.props.onChange(time); } _onMouseOver (index) { this.props.onChapterHover(index); } _renderChapterMarkers () { const { duration, timeline } = this.props; if (timeline) { let chapters = timeline.map((chapter, index, chapters) => { let percent = (chapter.time / duration) * 100; let tickClasses = classnames( `${CLASS_ROOT}__chapter-marker-tick`, { [`${CLASS_ROOT}__chapter-marker-tick-start`]: percent === 0 } ); return ( <div className={`${CLASS_ROOT}__chapter-marker`} key={chapter.time} style={{width: `${percent}%`}}> <div className={tickClasses} onMouseOver={this._onMouseOver.bind(this, index)} onMouseOut={this.props.onChapterHover} onFocus={this._onMouseOver.bind(this, index)} onBlur={this.props.onChapterHover} onClick={this._onChapterClick.bind(this, chapter.time)} /> <div className={`${CLASS_ROOT}__chapter-marker-track`} /> </div> ); }); return ( <div className={`${CLASS_ROOT}__chapter-markers`}> {chapters} </div> ); } } render () { const { progress, timeline, percentageBuffered } = this.props; const downloadProgress = ( <div style={{ width: `${percentageBuffered}%`, background: 'rgba(110,110,110,0.85)', }} /> ); return ( <Box pad="none" className={`${CLASS_ROOT}__progress`} direction="row"> <div className={`${CLASS_ROOT}__progress-bar-fill`} style={{ width: progress + '%', pointerEvents: 'none', }} /> {timeline ? this._renderChapterMarkers() : undefined} <input className={`${CLASS_ROOT}__progress-bar-input`} onChange={this._onProgressBarChange} onMouseUp={this._onProgressBarChange} type="range" min="0" max="100" step="0.1" /> {downloadProgress} </Box> ); } } ProgressBar.propTypes = { onClick: PropTypes.func, duration: PropTypes.number, progress: PropTypes.number, onChapterHover: PropTypes.func }; ProgressBar.defaultProps = { duration: 0, progress: 0 };
app/index.js
htanjo/server-app
// @flow import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
packages/components/src/Actions/ActionButton/Button.stories.js
Talend/ui
import React from 'react'; import { action } from '@storybook/addon-actions'; import withPropsCombinations from 'react-storybook-addon-props-combinations'; import ActionButton from './ActionButton.component'; import theme from './Button.stories.scss'; const myAction = { label: 'Click me', icon: 'talend-dataprep', 'data-feature': 'action', onClick: action('You clicked me'), }; const OverlayComponent = <div>I am an overlay</div>; const mouseDownAction = { label: 'Click me', icon: 'talend-dataprep', 'data-feature': 'action', onMouseDown: action('You clicked me'), }; const ACTION1 = 'Action 1'; const ACTION2 = 'Action 2'; class DisableActionButton extends React.Component { constructor(props) { super(props); this.state = { active: ACTION1, }; } render() { const props = { icon: 'talend-panel-opener-right', tooltipPlacement: 'top', tooltip: true, }; return ( <React.Fragment> <p>Switch Button</p> <ActionButton {...props} label={ACTION1} active={this.state.active === ACTION1} disabled={this.state.active === ACTION1} onClick={() => this.setState({ active: ACTION1 })} /> <ActionButton {...props} label={ACTION2} active={this.state.active === ACTION2} disabled={this.state.active === ACTION2} onClick={() => this.setState({ active: ACTION2 })} /> </React.Fragment> ); } } export default { title: 'Buttons/Button', decorators: [story => <div className="col-lg-offset-2 col-lg-8">{story()}</div>], }; export const DisableTheButtons = () => <DisableActionButton />; export const Default = () => ( <div> <h3>By default :</h3> <ActionButton id="default" {...myAction} /> <h3>Bootstrap style :</h3> <ActionButton id="bsStyle" {...myAction} bsStyle="primary" /> <ActionButton id="bsStyle" {...myAction} className="btn-primary btn-inverse" /> <h3>With hideLabel option</h3> <ActionButton id="hidelabel" {...myAction} hideLabel /> <h3>In progress</h3> <ActionButton id="inprogress" {...myAction} inProgress /> <h3>Loading</h3> <ActionButton id="loading" loading label="loading" /> <h3>Icon button with label</h3> <ActionButton id="icon" {...myAction} link /> <h3>Icon button without label</h3> <ActionButton id="icon-without-label" {...myAction} link label="" /> <h3>Loading Icon button</h3> <ActionButton id="icon" link label="Click me" loading /> <h3>Disabled</h3> <ActionButton id="disabled" {...myAction} disabled tooltip /> <h3>Reverse display</h3> <ActionButton id="reverseDisplay" {...myAction} iconPosition="right" /> <h3>With hover handlers</h3> <ActionButton id="withHoverHandlers" {...myAction} onMouseEnter={action('mouse enter')} onMouseLeave={action('mouse leave')} /> <h3>Transform icon</h3> <ActionButton id="reverseDisplay" {...myAction} iconTransform="rotate-180" /> <h3>Custom tooltip</h3> <ActionButton id="default" {...myAction} tooltipLabel="Custom label here" /> <h3>OnMouse down handler</h3> <ActionButton id="hidelabel" {...mouseDownAction} hideLabel /> <h3>Action with popover</h3> <ActionButton id="hidelabel" overlayId="hidelabel" overlayComponent={OverlayComponent} overlayPlacement="top" tooltipPlacement="right" {...mouseDownAction} hideLabel /> <h3>Action in progress</h3> <ActionButton id="hidelabel" inProgress overlayId="in-progress" overlayComponent={OverlayComponent} overlayPlacement="top" tooltipPlacement="right" {...mouseDownAction} hideLabel /> <h3>Automatic Dropup : this is contained in a restricted ".tc-dropdown-container" element.</h3> <div id="auto-dropup" className="tc-dropdown-container" style={{ border: '1px solid black', overflow: 'scroll', height: '300px', resize: 'vertical', }} > <p>Scroll me to set overflow on top or down of the container, then open the dropdown.</p> <div className={theme['storybook-wrapped-action']}> <ActionButton preventScrolling overlayId="scroll" overlayComponent={OverlayComponent} overlayPlacement="bottom" tooltipPlacement="right" {...mouseDownAction} hideLabel style={{ marginTop: '200px', marginBottom: '200px', }} /> </div> </div> </div> ); export const Combinations = withPropsCombinations(ActionButton, { label: ['Click me'], bsStyle: [ 'default', 'primary', 'success', 'info', 'warning', 'danger', 'link', 'info btn-inverse', ], icon: ['talend-dataprep'], 'data-feature': ['my.feature'], onClick: [action('You clicked me')], hideLabel: [false, true], inProgress: [true, false], disabled: [false, true], tooltip: [true], tooltipLabel: ['Tooltip custom label'], });
frontend/app/components/Phrasebook/create.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // import ProviderHelpers from 'common/ProviderHelpers' import StateLoading from 'components/Loading' import StateErrorBoundary from 'components/ErrorBoundary' import StateSuccessDefault from './states/successCreate' import StateCreate from './states/create' // Immutable import Immutable from 'immutable' // REDUX import { connect } from 'react-redux' // REDUX: actions/dispatch/func import { pushWindowPath } from 'reducers/windowPath' import { createCategory, fetchCategories } from 'reducers/fvCategory' import { fetchDialect } from 'reducers/fvDialect' import { getFormData, handleSubmit } from 'common/FormHelpers' import AuthenticationFilter from 'components/AuthenticationFilter' import PromiseWrapper from 'components/PromiseWrapper' import { STATE_LOADING, STATE_DEFAULT, STATE_ERROR, STATE_SUCCESS, STATE_ERROR_BOUNDARY, DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_LANGUAGE, DEFAULT_SORT_COL, DEFAULT_SORT_TYPE, } from 'common/Constants' import './Phrasebook.css' const { array, element, func, number, object, string } = PropTypes let categoriesPath = undefined export class Phrasebook extends React.Component { static propTypes = { className: string, copy: object, groupName: string, breadcrumb: element, DEFAULT_PAGE: number, DEFAULT_PAGE_SIZE: number, DEFAULT_LANGUAGE: string, DEFAULT_SORT_COL: string, DEFAULT_SORT_TYPE: string, validator: object, // REDUX: reducers/state routeParams: object.isRequired, computeCategories: object.isRequired, computeCreateCategory: object, computeCategory: object, computeDialect: object.isRequired, computeDialect2: object.isRequired, splitWindowPath: array.isRequired, // REDUX: actions/dispatch/func createCategory: func, fetchCategories: func.isRequired, fetchDialect: func.isRequired, pushWindowPath: func.isRequired, } static defaultProps = { className: 'FormPhrasebook', groupName: '', breadcrumb: null, DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_LANGUAGE, DEFAULT_SORT_COL, DEFAULT_SORT_TYPE, } _commonInitialState = { errors: [], formData: {}, isBusy: false, } state = { componentState: STATE_LOADING, is403: false, ...this._commonInitialState, } // NOTE: Using callback refs since on old React // https://reactjs.org/docs/refs-and-the-dom.html#callback-refs form = null setFormRef = (_element) => { this.form = _element } async componentDidMount() { const { routeParams } = this.props const { pageSize, page } = routeParams const copy = this.props.copy ? this.props.copy : await import(/* webpackChunkName: "PhrasebookCopy" */ './copy').then((_copy) => { return _copy.default }) categoriesPath = `${routeParams.dialect_path}/Phrase Books/` // Get data for computeDialect await this.props.fetchDialect('/' + this.props.routeParams.dialect_path) if (this.props.computeDialect.isError && this.props.computeDialect.error) { this.setState({ componentState: STATE_DEFAULT, // Note: Intentional == comparison is403: this.props.computeDialect.error == '403', copy, errorMessage: this.props.computeDialect.error, }) return } let currentAppliedFilter = '' // eslint-disable-line // TODO: ASK DANIEL ABOUT `filter` & `filter.currentAppliedFilter` // if (filter.has('currentAppliedFilter')) { // currentAppliedFilter = Object.values(filter.get('currentAppliedFilter').toJS()).join('') // } await this.props.fetchCategories( categoriesPath, `${currentAppliedFilter}&currentPageIndex=${page - 1}&pageSize=${pageSize}&sortOrder=${ this.props.DEFAULT_SORT_TYPE }&sortBy=${this.props.DEFAULT_SORT_COL}` ) const validator = this.props.validator ? this.props.validator : await import(/* webpackChunkName: "PhrasebookValidator" */ './validator').then((_validator) => { return _validator.default }) // Flip to ready state... this.setState({ componentState: STATE_DEFAULT, copy, validator, errorMessage: undefined, }) } render() { let content = null switch (this.state.componentState) { case STATE_LOADING: { content = this._stateGetLoading() break } case STATE_DEFAULT: { content = this._stateGetCreate() break } case STATE_ERROR: { content = this._stateGetError() break } case STATE_SUCCESS: { content = this._stateGetSuccess() break } case STATE_ERROR_BOUNDARY: { content = this._stateGetErrorBoundary() break } default: content = <div>{/* Shouldn't get here */}</div> } return content } _stateGetLoading = () => { const { className } = this.props return <StateLoading className={className} copy={this.state.copy} /> } _stateGetErrorBoundary = () => { return <StateErrorBoundary errorMessage={this.state.errorMessage} copy={this.state.copy} /> } _stateGetCreate = () => { const { className, breadcrumb, groupName } = this.props const { errors, isBusy } = this.state return ( <AuthenticationFilter.Container is403={this.state.is403} notAuthenticatedComponent={<StateErrorBoundary copy={this.state.copy} errorMessage={this.state.errorMessage} />} > <PromiseWrapper computeEntities={Immutable.fromJS([ { id: `/${this.props.routeParams.dialect_path}`, entity: this.props.fetchDialect, }, ])} > <StateCreate className={className} copy={this.state.copy} groupName={groupName} breadcrumb={breadcrumb} errors={errors} isBusy={isBusy} onRequestSaveForm={() => { this._onRequestSaveForm() }} setFormRef={this.setFormRef} /> </PromiseWrapper> </AuthenticationFilter.Container> ) } _stateGetError = () => { // _stateGetCreate() also handles errors, so just call it... return this._stateGetCreate() } _stateGetSuccess = () => { const { className } = this.props const { formData, itemUid } = this.state return ( <StateSuccessDefault className={className} copy={this.state.copy} formData={formData} itemUid={itemUid} handleClick={() => { this.setState({ componentState: STATE_DEFAULT, ...this._commonInitialState, }) }} /> ) } _handleCreateItemSubmit = async (formData) => { // Submit here const now = Date.now() const name = formData['dc:title'] const results = await this.props.createCategory( `${this.props.routeParams.dialect_path}/Phrase Books`, // parentDoc: { // docParams: type: 'FVCategory', name: name, properties: { 'dc:description': formData['dc:description'], 'dc:title': formData['dc:title'], }, }, null, now ) if (results.success === false) { this.setState({ componentState: STATE_ERROR_BOUNDARY, }) return } const response = results ? results.response : {} if (response && response.uid) { this.setState({ errors: [], formData, itemUid: response.uid, componentState: STATE_SUCCESS, categoryPath: `${this.props.routeParams.dialect_path}/Categories/${formData['dc:title']}.${now}`, }) } else { this.setState({ componentState: STATE_ERROR_BOUNDARY, }) } } _onRequestSaveForm = async () => { const formData = getFormData({ formReference: this.form, }) const valid = () => { this.setState( { isBusy: true, }, () => { this._handleCreateItemSubmit(formData) } ) } const invalid = (response) => { this.setState({ errors: response.errors, componentState: STATE_ERROR, }) } handleSubmit({ validator: this.state.validator, formData, valid, invalid, }) } } // REDUX: reducers/state const mapStateToProps = (state /*, ownProps*/) => { const { fvCategory, fvDialect, windowPath, navigation } = state const { computeCategories, computeCreateCategory, computeCategory } = fvCategory const { computeDialect, computeDialect2 } = fvDialect const { splitWindowPath } = windowPath const { route } = navigation return { computeCategories, computeCreateCategory, computeCategory, routeParams: route.routeParams, computeDialect, computeDialect2, splitWindowPath, } } // REDUX: actions/dispatch/func const mapDispatchToProps = { createCategory, fetchCategories, fetchDialect, pushWindowPath, } export default connect(mapStateToProps, mapDispatchToProps)(Phrasebook)
docs/src/GettingStartedPage.js
yuche/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; export default class Page extends React.Component { render() { return ( <div> <NavMain activePage="getting-started" /> <PageHeader title="Getting started" subTitle="An overview of React-Bootstrap and how to install and use." /> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <h2 id="setup" className="page-header">Setup</h2> <p className="lead">You can import the lib as AMD modules, CommonJS modules, or as a global JS script.</p> <p>First add the Bootstrap CSS to your project; check <a href="http://getbootstrap.com/getting-started/" name="Bootstrap Docs">here</a> if you have not already done that. Note that:</p> <ul> <li>Because many folks use custom Bootstrap themes, we do not directly depend on Bootstrap. It is up to you to to determine how you get and link to the Bootstrap CSS and fonts.</li> <li>React-Bootstrap doesn't depend on a very precise version of Bootstrap. Just pull the latest and, in case of trouble, take hints on the version used by this documentation page. Then, have Bootstrap in your dependencies and ensure your build can read your Less/Sass/SCSS entry point.</li> </ul> <p>Then:</p> <h3>CommonJS</h3> <div className="highlight"> <CodeExample codeText={ `$ npm install react $ npm install react-bootstrap` } /> <br /> <CodeExample mode="javascript" codeText={ `var Alert = require('react-bootstrap/lib/Alert'); // or var Alert = require('react-bootstrap').Alert; // with ES6 modules import Alert from 'react-bootstrap/lib/Alert'; // or import {Alert} from 'react-bootstrap';` } /> </div> <h3>AMD</h3> <div className="highlight"> <CodeExample codeText={ `$ bower install react $ bower install react-bootstrap` } /> <br /> <CodeExample mode="javascript" codeText={ `define(['react-bootstrap/lib/Alert'], function(Alert) { ... }); // or define(['react-bootstrap'], function(ReactBootstrap) { var Alert = ReactBootstrap.Alert; ... });` } /> </div> <h3>Browser globals</h3> <p>The bower repo contains <code>react-bootstrap.js</code> and <code>react-bootstrap.min.js</code> with all components exported in the <code>window.ReactBootstrap</code> object.</p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react.js"></script> <script src="path/to/react-bootstrap-bower/react-bootstrap.min.js"></script> <script> var Alert = ReactBootstrap.Alert; </script>` } /> </div> <h3>Without JSX</h3> <p>If you do not use JSX and just call components as functions, you must explicitly <a href="https://facebook.github.io/react/blog/2014/10/14/introducing-react-elements.html#deprecated-auto-generated-factories">create a factory before calling it</a>. React-bootstrap provides factories for you in <code>lib/factories</code>:</p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var Alert = require('react-bootstrap/lib/factories').Alert; // or var Alert = require('react-bootstrap/lib/factories/Alert');` } /> </div> </div> <div className="bs-docs-section"> <h2 id="browser-support" className="page-header">Browser support</h2> <p>We aim to support all browsers supported by both <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">React</a> and <a href="http://getbootstrap.com/getting-started/#support">Bootstrap</a>.</p> <p>React requires <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">polyfills for non-ES5 capable browsers.</a></p> <p><a href="http://jquery.com">jQuery</a> is currently required only for IE8 support for components which require reading element positions from the DOM: <code>Popover</code> and <code>Tooltip</code> when launched with <code>OverlayTrigger</code>. We would like to remove this dependency in future versions but for now, including the following snippet in your page should have you covered:</p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<!--[if lt IE 9]> <script> (function(){ var ef = function(){}; window.console = window.console || {log:ef,warn:ef,error:ef,dir:ef}; }()); </script> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` } /> </div> </div> </div> </div> </div> <PageFooter /> </div> ); } shouldComponentUpdate() { return false; } }
app/containers/App/index.js
bsherrill480/website-asd-init
/** * * App * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import Header from 'containers/Header'; import Footer from 'components/Footer'; import withProgressBar from 'components/ProgressBar'; const AppWrapper = styled.div` `; export function App(props) { return ( <AppWrapper> <Helmet titleTemplate="%s - React.js Boilerplate" defaultTitle="React.js Boilerplate" meta={[ { name: 'description', content: 'A React.js Boilerplate application' }, ]} /> <Header /> <div className="container"> {React.Children.toArray(props.children)} </div> <Footer /> </AppWrapper> ); } App.propTypes = { children: React.PropTypes.node, }; export default withProgressBar(App);
admin/client/App/shared/Popout/PopoutList.js
cermati/keystone
/** * Render a popout list. Can also use PopoutListItem and PopoutListHeading */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; const PopoutList = React.createClass({ displayName: 'PopoutList', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, }, render () { const className = classnames('PopoutList', this.props.className); const props = blacklist(this.props, 'className'); return ( <div className={className} {...props} /> ); }, }); module.exports = PopoutList; // expose the child to the top level export module.exports.Item = require('./PopoutListItem'); module.exports.Heading = require('./PopoutListHeading');
src/components/TodoInput.js
johny/react-redux-todo-app
import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions/actions.js'; let TodoInput = ({dispatch}) => { // key handler for input const onKeyUp = (event) => { if (event.keyCode === 13) { let input = event.target; dispatch(addTodo(input.value)) input.value = ''; } }; return ( <div className="todo-input"> <input type="text" className="todo-input__input" placeholder="What do you want to do today..." onKeyUp={onKeyUp} /> </div> ); }; TodoInput = connect()(TodoInput); export default TodoInput;
client/modules/App/__tests__/App.spec.js
phumberdroz/pizzastore
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { shallow, mount } from 'enzyme'; import { App } from '../App'; import styles from '../App.css'; import { toggleAddPost } from '../AppActions'; const children = <h1>Test</h1>; const dispatch = sinon.spy(); const props = { children, dispatch, }; test('renders properly', t => { const wrapper = shallow( <App {...props} /> ); // t.is(wrapper.find('Helmet').length, 1); t.is(wrapper.find('Header').length, 1); t.is(wrapper.find('Footer').length, 1); t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection); t.truthy(wrapper.find('Header + div').hasClass(styles.container)); t.truthy(wrapper.find('Header + div').children(), children); }); test('calls componentDidMount', t => { sinon.spy(App.prototype, 'componentDidMount'); mount( <App {...props} />, { context: { router: { isActive: sinon.stub().returns(true), push: sinon.stub(), replace: sinon.stub(), go: sinon.stub(), goBack: sinon.stub(), goForward: sinon.stub(), setRouteLeaveHook: sinon.stub(), createHref: sinon.stub(), }, }, childContextTypes: { router: React.PropTypes.object, }, }, ); t.truthy(App.prototype.componentDidMount.calledOnce); App.prototype.componentDidMount.restore(); }); test('calling toggleAddPostSection dispatches toggleAddPost', t => { const wrapper = shallow( <App {...props} /> ); wrapper.instance().toggleAddPostSection(); t.truthy(dispatch.calledOnce); t.truthy(dispatch.calledWith(toggleAddPost())); });
stories/babylonjs/Integrations/reactSpring.stories.js
brianzinn/react-babylonJS
import React from 'react' import { Engine, Scene, useHover, CustomPropsHandler, PropChangeType, useCustomPropsHandler, } from '../../../dist/react-babylonjs' import { Vector3, Color3 } from '@babylonjs/core/Maths/math'; import { useSprings, useSpring, animated } from 'react-babylon-spring'; import 'react-babylon-spring'; import '../../style.css' export default {title: 'Integrations'}; /** * Only need these Handlers or otherwise react-babylon-spring can export them. * Copied from /src/customProps in that repo. * The global resolution that used to work likely broke when not re-using the same Fiber host was fixed in issue #100 (new renderer creation). */ function parseRgbaString(rgba) { const arr = rgba.replace(/[^\d,]/g, '').split(','); return arr.map(num => parseInt(num, 10) / 255); } const Key = 'react-babylon-spring'; class CustomColor3StringHandler { get name() { return `${Key}:Color3String` } get propChangeType() { return PropChangeType.Color3; } accept(newProp) { // console.log('accept Color3String?', newProp); return typeof (newProp) === 'string'; } process(oldProp, newProp) { if (oldProp !== newProp) { return { processed: true, value: Color3.FromArray(parseRgbaString(newProp)) }; } return {processed: false, value: null}; } } class CustomColor3ArrayHandler { get name() { return `${Key}:Color3Array` } get propChangeType() { return PropChangeType.Color3; } accept(newProp) { // console.log('accept Color3Array?:', Array.isArray(newProp), newProp); return Array.isArray(newProp); } process(oldProp, ) { if (oldProp === undefined || oldProp.length !== newProp.length) { console.log(`found diff length (${oldProp?.length}/${newProp?.length}) Color3Array new? ${oldProp === undefined}`) return { processed: true, value: Color3.FromArray(newProp) }; } for (let i = 0; i < oldProp.length; i++) { if (oldProp[i] !== newProp[i]) { console.log('found diff value Color3Array', oldProp, newProp); return { processed: true, value: Color3.FromArray(newProp) }; } } // console.log('Color3Array not processed', oldProp, newProp); return {processed: false, value: null}; } } class CustomColor4StringHandler { get name() { return `${Key}:Color4String` } get propChangeType() { return PropChangeType.Color4; } accept(newProp) { return typeof (newProp) === 'string'; } process(oldProp, newProp) { if (oldProp !== newProp) { // console.log('found diff Color4String') return { processed: true, value: Color4.FromArray(parseRgbaString(newProp)) }; } return {processed: false, value: null}; } } class CustomVector3ArrayHandler { get name() { return `${Key}:Vector3Array` } get propChangeType() { return PropChangeType.Vector3; } accept(newProp) { // console.log('Vector3: newProp:', newProp, Array.isArray(newProp)); return Array.isArray(newProp); } process(oldProp, newProp) { if (oldProp === undefined || oldProp.length !== newProp.length) { // console.log(`found diff length (${oldProp?.length}/${newProp?.length}) Color3Array new? ${oldProp === undefined}`) return { processed: true, value: Vector3.FromArray(newProp) }; } for (let i = 0; i < oldProp.length; i++) { if (oldProp[i] !== newProp[i]) { // console.log('found difference...', oldProp, newProp); return { processed: true, value: Vector3.FromArray(newProp) }; } } // console.log('not processed...'); return {processed: false, value: null}; } } /** * This is the end of code that needed to be copied, since it is not exported. */ CustomPropsHandler.RegisterPropsHandler(new CustomColor3StringHandler()); CustomPropsHandler.RegisterPropsHandler(new CustomColor3ArrayHandler()); CustomPropsHandler.RegisterPropsHandler(new CustomColor4StringHandler()); CustomPropsHandler.RegisterPropsHandler(new CustomVector3ArrayHandler()); const getRandomColor = (function () { // const Colors = ['#4F86EC', '#D9503F', '#F2BD42', '#58A55C']; const Colors = [[0.31, 0.53, 0.93, 1], [0.85, 0.31, 0.25, 1], [0.95, 0.74, 0.26, 1], [0.35, 0.65, 0.36, 1]]; let i = 0; return () => { i++; return Colors[i % Colors.length]; } })(); function getCyclePosition(i, blankRadius) { i += blankRadius; let angle = i % Math.PI * 2; const x = i * Math.cos(angle); const z = i * Math.sin(angle); return [x, z]; } const WithSpring = () => { const [props, set] = useSprings(100, i => { const [x, z] = getCyclePosition(i, 30); return { position: [x, 20, z], color: getRandomColor(), from: { position: [x, Math.random() * 50 - 60, z], }, config: { duration: 3000, } } }); const [ref, isHovering] = useHover(_ => { set((index, ctrl) => { return { color: getRandomColor(), position: [0, 20, 0], config: { duration: 2000, } } }); }, _ => { set(i => { const [x, z] = getCyclePosition(i, 30); return { position: [x, 20, z], config: { duration: 2000, } } }); }); const groupProps = useSpring({ rotation: isHovering ? [0, Math.PI * 2, 0] : [0, 0, 0], config: { duration: 2000 } }); return ( <> <freeCamera name='camera1' position={new Vector3(0, 200, -200)} setTarget={[Vector3.Zero()]}/> <hemisphericLight name='light1' intensity={0.7} direction={Vector3.Up()}/> <animated.transformNode name='' rotation={groupProps.rotation}> { props.map(({position, color}, i) => <animated.box key={i} name='' width={6} height={16} depth={6} position={position}> <animated.standardMaterial name='' diffuseColor={color}/> </animated.box> ) } </animated.transformNode> <sphere ref={ref} name='' diameter={40} position={new Vector3(0, 20, 0)}> <standardMaterial name='' diffuseColor={new Color3(0.3, 0.6, 0.9)} alpha={0.8} /> </sphere> <ground name='ground1' width={1000} height={1000} subdivisions={2}/> </> ) } export const ReactSpring = () => ( <div style={{flex: 1, display: 'flex'}}> <Engine antialias adaptToDeviceRatio canvasId='babylonJS'> <Scene> <WithSpring/> </Scene> </Engine> </div> ); ReactSpring.story = { name: 'react-spring' }
packages/react-scripts/template/src/App.js
sThig/jabbascrypt
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
app/javascript/mastodon/features/bookmarked_statuses/index.js
h3zjp/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchBookmarkedStatuses, expandBookmarkedStatuses } from '../../actions/bookmarks'; import Column from '../ui/components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import StatusList from '../../components/status_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { debounce } from 'lodash'; const messages = defineMessages({ heading: { id: 'column.bookmarks', defaultMessage: 'Bookmarks' }, }); const mapStateToProps = state => ({ statusIds: state.getIn(['status_lists', 'bookmarks', 'items']), isLoading: state.getIn(['status_lists', 'bookmarks', 'isLoading'], true), hasMore: !!state.getIn(['status_lists', 'bookmarks', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Bookmarks extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, isLoading: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchBookmarkedStatuses()); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('BOOKMARKS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = debounce(() => { this.props.dispatch(expandBookmarkedStatuses()); }, 300, { leading: true }) render () { const { intl, shouldUpdateScroll, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.bookmarked_statuses' defaultMessage="You don't have any bookmarked toots yet. When you bookmark one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}> <ColumnHeader icon='bookmark' title={intl.formatMessage(messages.heading)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusList trackScroll={!pinned} statusIds={statusIds} scrollKey={`bookmarked_statuses-${columnId}`} hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} /> </Column> ); } }
src/MessageBox/MessageBoxFixedHeaderFooter.js
skyiea/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import * as styles from './MessageBoxFixedHeaderFooter.scss'; import WixComponent from '../BaseComponents/WixComponent'; class MessageBoxFixedHeaderFooter extends WixComponent { render() { const { children, width, prefixContent, suffixContent, footer, header } = this.props; const customHeader = header && <div className={styles.header}> {header} </div>; const customPrefixContent = prefixContent && <div className={styles['prefix-content']}> {prefixContent} </div>; const customSuffixContent = suffixContent && <div className={styles['prefix-content']}> {suffixContent} </div>; const customFooter = footer && <div className={styles.footer}> {footer} </div>; return ( <div className={styles.content} style={{width}}> {customHeader} {customPrefixContent} <div className={styles.body}> {children} </div> {customSuffixContent} {customFooter} </div> ); } } MessageBoxFixedHeaderFooter.propTypes = { width: PropTypes.string, footer: PropTypes.node, header: PropTypes.node, children: PropTypes.any, prefixContent: PropTypes.node, sufixContent: PropTypes.node }; MessageBoxFixedHeaderFooter.defaultProps = { width: '600px' }; export default MessageBoxFixedHeaderFooter;
information/blendle-frontend-react-source/app/components/UserTooltip.js
BramscoChill/BlendleParser
import { includes } from 'lodash'; import React from 'react'; import PropTypes from 'prop-types'; import Link from 'components/Link'; import Translate from 'components/shared/Translate'; import FollowButton from 'components/buttons/Follow'; import Auth from 'controllers/auth'; import AvatarImage from 'components/AvatarImage'; import { STAFFPICKS } from 'app-constants'; export default class extends React.Component { static propTypes = { user: PropTypes.object.isRequired, analytics: PropTypes.object.isRequired, }; render() { return ( <div className={`v-user-tooltip user-id-${this.props.user.id}`}> <div className="hovercard-top"> <AvatarImage src={this.props.user.getAvatarHref()} animate /> <div className="gradient" /> <h1 className="user-name"> <Link href={`/user/${this.props.user.id}`}>{this.props.user.get('username')}</Link> </h1> </div> <div className="hovercard-bottom"> {this._renderBio()} {this._renderUserInfo()} {this._renderFollowButton()} </div> </div> ); } _renderBio = () => { const userBio = this.props.user.getBioHTML(); if (!userBio) { return; } return <div className="bio" dangerouslySetInnerHTML={{ __html: userBio }} />; }; _renderUserInfo = () => { if (includes(STAFFPICKS, this.props.user.id)) { return; } return ( <div className="user-info"> <div className="info-followers"> <span className="user-info-amount">{this.props.user.getFormattedFollowers()}</span> <Translate find="user.captions.followers" className="user-info-title" /> </div> <div className="info-posts"> <span className="user-info-amount">{this.props.user.get('posts')}</span> <Translate find="user.captions.shared" className="user-info-title" /> </div> </div> ); }; _renderFollowButton = () => { if (Auth.getId() === this.props.user.id || includes(STAFFPICKS, this.props.user.id)) { return; } return <FollowButton user={this.props.user} analytics={this.props.analytics} size="small" />; }; } // WEBPACK FOOTER // // ./src/js/app/components/UserTooltip.js
examples/fractals/index.js
elpic/react-pdf
/* eslint react/prop-types: 0, react/jsx-sort-props: 0 */ import React from 'react'; import ReactPDF from '../../packages/react-pdf-node'; import { Page, Document } from '../../packages/react-pdf'; import Fractal from './Fractal'; const doc = ( <Document title="Fractals" author="John Doe" subject="Rendering fractals with react-pdf" keywords={['react', 'pdf', 'fractals']} > <Page size="A4"> <Fractal steps={18} /> </Page> <Page orientation="landscape" size="A4"> <Fractal steps={14} /> </Page> <Page size="B4"> <Fractal steps={10} /> </Page> </Document> ); ReactPDF.render(doc, `${__dirname}/output.pdf`, () => { console.log('Fractals rendered!'); });
packages/web/src/components/Markdown/Markdown.js
hengkx/note
import React from 'react'; import PropTypes from 'prop-types'; import MarkdownIt from 'markdown-it'; import markdownItTaskLists from 'markdown-it-task-lists'; import markdownItGithubToc from 'markdown-it-github-toc'; import markdownItFootnote from 'markdown-it-footnote'; import markdownItDeflist from 'markdown-it-deflist'; import hljs from 'highlight.js'; import 'highlight.js/styles/github.css'; import './less/markdown.less'; const md = new MarkdownIt({ highlight: (str, lang) => { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(lang, str).value; } catch (error) { console.log(error); } } return ''; // use external default escaping } }).use(markdownItTaskLists) .use(markdownItGithubToc, { tocFirstLevel: 2, tocLastLevel: 3, tocClassName: 'toc', anchorLinkSymbol: '', anchorLinkSpace: false, anchorClassName: 'anchor', anchorLinkSymbolClassName: 'octicon octicon-link' }) .use(markdownItFootnote) .use(markdownItDeflist); const Markdown = ({ content }) => ( <div className="markdown-body" dangerouslySetInnerHTML={{ __html: md.render(content) }} /> // eslint-disable-line react/no-danger ); Markdown.propTypes = { content: PropTypes.string }; export default Markdown;
src/Avatar/Avatar.js
ctco/rosemary-ui
import React from 'react'; import PropTypes from 'prop-types'; const PROPERTY_TYPES = { text: PropTypes.string, avatarImgUrl: PropTypes.string, testId: PropTypes.any }; class Avatar extends React.Component { render() { return ( <div data-test-id={this.props.testId} className="avatar"> {this.props.avatarImgUrl ? ( <img className="avatar__img" src={this.props.avatarImgUrl} /> ) : ( this.props.text )} </div> ); } } Avatar.propTypes = PROPERTY_TYPES; export default Avatar;
src/svg-icons/action/thumb-up.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionThumbUp = (props) => ( <SvgIcon {...props}> <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/> </SvgIcon> ); ActionThumbUp = pure(ActionThumbUp); ActionThumbUp.displayName = 'ActionThumbUp'; ActionThumbUp.muiName = 'SvgIcon'; export default ActionThumbUp;
src/Game/UI/Panel/Save.js
digijin/space-station-sim
// @flow import * as engine from 'Game/engine'; import { connect } from 'react-redux'; import React from 'react'; import Draggable from 'react-draggable' import Header from './Component/Header' import listSaves from 'Game/State/listSaves' import save from 'Game/State/save' import load from 'Game/State/load' class SavePanel extends React.Component { state:{savename:string} constructor(props) { super(props); this.state = {'savename': 'savename'}; } load(savename:string){ load(savename); } save(savename:string){ save(savename) this.forceUpdate() } render() { let saves = listSaves(); saves = saves.map(s => { return <button id={'load-'+s} key={s} onClick={() => {this.load(s)}}>{s}</button> }) return <div className="save panel"> <Header text='Save Panel' close={this.props.close} /> {saves} <hr /> new save: <input type="text" value={this.state.savename} onChange={(e)=>{ this.setState({savename: e.target.value}); }} /> <button id="save" onClick={() => {this.save(this.state.savename)}}>save</button> </div> } } function mapStateToProps(state:Object, props:Object):Object { return { }; } function mapDispatchToProps(dispatch:Function, props:Object):Object { return { close: () => { dispatch({type:'TOGGLE_SAVE_PANEL'}); } }; } export default connect(mapStateToProps, mapDispatchToProps)(SavePanel);
src/Parser/Warrior/Fury/CONFIG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Maldark } from 'MAINTAINERS'; import SPECS from 'common/SPECS'; import SPEC_ANALYSIS_COMPLETENESS from 'common/SPEC_ANALYSIS_COMPLETENESS'; import CombatLogParser from './CombatLogParser'; import CHANGELOG from './CHANGELOG'; export default { spec: SPECS.FURY_WARRIOR, maintainers: [Maldark], description: ( <div> The Fury Warrior parser only holds very basic functionality. Currently does not analyze legendaries, cast sequence or tier bonuses. </div> ), // good = it matches most common manual reviews in class discords, great = it support all important class features completeness: SPEC_ANALYSIS_COMPLETENESS.NEEDS_MORE_WORK, specDiscussionUrl: 'https://github.com/WoWAnalyzer/WoWAnalyzer/milestone/13', // Shouldn't have to change these: changelog: CHANGELOG, parser: CombatLogParser, // used for generating a GitHub link directly to your spec path: __dirname, };
js/components/tab/basicTab.js
onderveli/EmlakAPP
import React, { Component } from 'react'; import { Container, Header, Title, Button, Icon, Tabs, Tab, Right, Left, Body } from 'native-base'; import TabOne from './tabOne'; import TabTwo from './tabTwo'; import TabThree from './tabThree'; class BasicTab extends Component { // eslint-disable-line render() { return ( <Container> <Header hasTabs> <Left> <Button transparent onPress={() => this.props.navigation.goBack()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title> Basic Tabs</Title> </Body> <Right /> </Header> <Tabs> <Tab heading="Tab1"> <TabOne /> </Tab> <Tab heading="Tab2"> <TabTwo /> </Tab> <Tab heading="Tab3"> <TabThree /> </Tab> </Tabs> </Container> ); } } export default BasicTab;
src/Components/Foot.js
jsmankoo/SPATemplate
import React from 'react'; import {connect} from 'react-redux'; import MediaQuery from 'react-responsive'; import marked from 'marked'; const Foot = ({Copyright,Information,Developer,Facebook,Twitter,Instagram})=>( <div className='Foot'> <MediaQuery maxDeviceWidth={767}> <div className="Mobile"> <div className="Copyright" dangerouslySetInnerHTML={{__html:marked(Copyright)}} /> <div className="SocialMedia"> <a target='_blank' href={Facebook}> <i className='fab fab-facebook-alt' /> </a> <a target='_blank' href={Twitter}> <i className='fab fab-twitter' /> </a> <a target='_blank' href={Instagram}> <i className='fab fab-instagram' /> </a> </div> <div className="Information" dangerouslySetInnerHTML={{__html:marked(Information)}} /> <div className="Developer" dangerouslySetInnerHTML={{__html:marked(Developer)}} /> </div> </MediaQuery> <MediaQuery minDeviceWidth={768}> <div className="Tablet"> <div className="Copyright" dangerouslySetInnerHTML={{__html:marked(`${Copyright}<br />${Information}`)}} /> <div className="SocialMedia"> <a target='_blank' href={Facebook}> <i className='fab fab-facebook-alt' /> </a> <a target='_blank' href={Twitter}> <i className='fab fab-twitter' /> </a> <a target='_blank' href={Instagram}> <i className='fab fab-instagram' /> </a> </div> <div className="Developer" dangerouslySetInnerHTML={{__html:marked(Developer)}} /> </div> </MediaQuery> </div> ); const mapStateToProps = ({Foot})=>{ return { Copyright: Foot.get('Copyright'), Information: Foot.get('Information'), Developer: Foot.get('Developer'), Facebook: Foot.get('Facebook'), Twitter: Foot.get('Twitter'), Instagram: Foot.get('Instagram') }; }; export default connect(mapStateToProps)(Foot);
packages/react-devtools-shared/src/devtools/views/Components/HocBadges.js
rickbeerendonk/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import { ElementTypeForwardRef, ElementTypeMemo, } from 'react-devtools-shared/src/types'; import styles from './HocBadges.css'; import type {Element} from './types'; type Props = {| element: Element, |}; export default function HocBadges({element}: Props) { const {hocDisplayNames, type} = ((element: any): Element); let typeBadge = null; if (type === ElementTypeMemo) { typeBadge = 'Memo'; } else if (type === ElementTypeForwardRef) { typeBadge = 'ForwardRef'; } if (hocDisplayNames === null && typeBadge === null) { return null; } return ( <div className={styles.HocBadges}> {typeBadge !== null && <div className={styles.Badge}>{typeBadge}</div>} {hocDisplayNames !== null && hocDisplayNames.map(hocDisplayName => ( <div key={hocDisplayName} className={styles.Badge}> {hocDisplayName} </div> ))} </div> ); }
information/blendle-frontend-react-source/app/components/notifications/PremiumCanceledNotification.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import { Notification, NotificationTitle, NotificationBody } from '@blendle/lego'; const PremiumCanceledNotification = ({ endDate, ...rest }) => ( <Notification {...rest}> <NotificationTitle>Je abonnement is beëindigd</NotificationTitle> <NotificationBody> Blendle Premium stopt per {endDate}. Tot die tijd kan je nog blijven lezen. </NotificationBody> </Notification> ); PremiumCanceledNotification.propTypes = { endDate: PropTypes.string.isRequired, }; export default PremiumCanceledNotification; // WEBPACK FOOTER // // ./src/js/app/components/notifications/PremiumCanceledNotification.js
frontend/src/Calendar/iCal/CalendarLinkModalContent.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Form from 'Components/Form/Form'; import FormGroup from 'Components/Form/FormGroup'; import FormInputButton from 'Components/Form/FormInputButton'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import Icon from 'Components/Icon'; import Button from 'Components/Link/Button'; import ClipboardButton from 'Components/Link/ClipboardButton'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { icons, inputTypes, kinds, sizes } from 'Helpers/Props'; function getUrls(state) { const { unmonitored, pastDays, futureDays, tags } = state; let icalUrl = `${window.location.host}${window.Lidarr.urlBase}/feed/v1/calendar/Lidarr.ics?`; if (unmonitored) { icalUrl += 'unmonitored=true&'; } if (tags.length) { icalUrl += `tags=${tags.toString()}&`; } icalUrl += `pastDays=${pastDays}&futureDays=${futureDays}&apikey=${window.Lidarr.apiKey}`; const iCalHttpUrl = `${window.location.protocol}//${icalUrl}`; const iCalWebCalUrl = `webcal://${icalUrl}`; return { iCalHttpUrl, iCalWebCalUrl }; } class CalendarLinkModalContent extends Component { // // Lifecycle constructor(props, context) { super(props, context); const defaultState = { unmonitored: false, pastDays: 7, futureDays: 28, tags: [] }; const urls = getUrls(defaultState); this.state = { ...defaultState, ...urls }; } // // Listeners onInputChange = ({ name, value }) => { const state = { ...this.state, [name]: value }; const urls = getUrls(state); this.setState({ [name]: value, ...urls }); } onLinkFocus = (event) => { event.target.select(); } // // Render render() { const { onModalClose } = this.props; const { unmonitored, pastDays, futureDays, tags, iCalHttpUrl, iCalWebCalUrl } = this.state; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> Lidarr Calendar Feed </ModalHeader> <ModalBody> <Form> <FormGroup> <FormLabel>Include Unmonitored</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="unmonitored" value={unmonitored} helpText="Include unmonitored albums in the iCal feed" onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>Past Days</FormLabel> <FormInputGroup type={inputTypes.NUMBER} name="pastDays" value={pastDays} helpText="Days for iCal feed to look into the past" onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>Future Days</FormLabel> <FormInputGroup type={inputTypes.NUMBER} name="futureDays" value={futureDays} helpText="Days for iCal feed to look into the future" onChange={this.onInputChange} /> </FormGroup> <FormGroup> <FormLabel>Tags</FormLabel> <FormInputGroup type={inputTypes.TAG} name="tags" value={tags} helpText="Feed will only contain artists with at least one matching tag" onChange={this.onInputChange} /> </FormGroup> <FormGroup size={sizes.LARGE} > <FormLabel>iCal Feed</FormLabel> <FormInputGroup type={inputTypes.TEXT} name="iCalHttpUrl" value={iCalHttpUrl} readOnly={true} helpText="Copy this URL to your client(s) or click to subscribe if your browser supports webcal" buttons={[ <ClipboardButton key="copy" value={iCalHttpUrl} kind={kinds.DEFAULT} />, <FormInputButton key="webcal" kind={kinds.DEFAULT} to={iCalWebCalUrl} target="_blank" noRouter={true} > <Icon name={icons.CALENDAR_O} /> </FormInputButton> ]} onChange={this.onInputChange} onFocus={this.onLinkFocus} /> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button onPress={onModalClose}> Close </Button> </ModalFooter> </ModalContent> ); } } CalendarLinkModalContent.propTypes = { tagList: PropTypes.arrayOf(PropTypes.object).isRequired, onModalClose: PropTypes.func.isRequired }; export default CalendarLinkModalContent;
example/pages/icons/index.js
n7best/react-weui
import React from 'react'; import {Icon} from '../../../build/packages'; import Page from '../../component/page'; import './icons.less'; const IconBox = (props) => ( <div className="icon-box"> {props.icon} <div className="icon-box__ctn"> <h3 className="icon-box__title">{props.title}</h3> <p className="icon-box__desc">{props.desc}</p> </div> </div> ) export default class IconDemo extends React.Component { render() { return ( <Page className="icons" title="Icons" subTitle="图标"spacing> <IconBox icon={<Icon size="large" value="success" />} title="Well done!" desc="You successfully read this important alert message." /> <IconBox icon={<Icon size="large" value="info" />} title="Heads up!" desc="This alert needs your attention, but it's not super important." /> <IconBox icon={<Icon size="large" value="warn" primary/>} title="Attention!" desc="This is your default warning with the primary property" /> <IconBox icon={<Icon size="large" value="warn"/>} title="Attention!" desc="This is your strong warning without the primary property" /> <IconBox icon={<Icon size="large" value="waiting"/>} title="Hold on!" desc="We are working hard to bring the best ui experience" /> <Icon size="large" value="safe-success" /> <Icon size="large" value="safe-warn" /> <div className="icon_sp_area"> <Icon value="success" /> <Icon value="success-circle" /> <Icon value="success-no-circle" /> <Icon value="info" /> <Icon value="waiting" /> <Icon value="waiting-circle" /> <Icon value="circle" /> <Icon value="warn" /> <Icon value="download" /> <Icon value="info-circle" /> <Icon value="cancel" /> <Icon value="clear" /> <Icon value="search" /> </div> </Page> ); } };
Realization/frontend/czechidm-core/src/content/automaticrole/attribute/AutomaticRoleAttributeRuleDetail.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import _ from 'lodash'; // import * as Basic from '../../../components/basic'; import * as Advanced from '../../../components/advanced'; import { AutomaticRoleAttributeRuleManager, FormAttributeManager, FormDefinitionManager } from '../../../redux'; import AutomaticRoleAttributeRuleTypeEnum from '../../../enums/AutomaticRoleAttributeRuleTypeEnum'; import AutomaticRoleAttributeRuleComparisonEnum from '../../../enums/AutomaticRoleAttributeRuleComparisonEnum'; import ContractStateEnum from '../../../enums/ContractStateEnum'; import AbstractEnum from '../../../enums/AbstractEnum'; /** * Constant for get eav attribute for identity contract * @type {String} */ const CONTRACT_EAV_TYPE = 'eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract'; /** * Constatn for get eav attribute for identity * @type {String} */ const IDENTITY_EAV_TYPE = 'eu.bcvsolutions.idm.core.model.entity.IdmIdentity'; const DEFINITION_TYPE_FILTER = 'definitionType'; const formDefinitionManager = new FormDefinitionManager(); /** * Modified ContractAttributeEnum - singular properties * * TODO: DRY, but how to generalize enum + static methods ... * * @author Ondrej Kopr */ class ContractAttributeEnum extends AbstractEnum { static getNiceLabel(key) { return super.getNiceLabel(`core:enums.ContractAttributeEnum.${key}`); } static findKeyBySymbol(sym) { return super.findKeyBySymbol(this, sym); } static findSymbolByKey(key) { return super.findSymbolByKey(this, key); } static getField(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { case this.POSITION: { return 'position'; } case this.EXTERNE: { return 'externe'; } case this.MAIN: { return 'main'; } case this.DESCRIPTION: { return 'description'; } case this.STATE: { return 'state'; } default: { return null; } } } static getEnum(field) { if (!field) { return null; } switch (field) { case 'position': { return this.POSITION; } case 'externe': { return this.EXTERNE; } case 'main': { return this.MAIN; } case 'description': { return this.DESCRIPTION; } case 'disabled': { return this.DISABLED; } case 'state': { return this.STATE; } default: { return null; } } } static getLevel(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { default: { return 'default'; } } } } ContractAttributeEnum.MAIN = Symbol('MAIN'); ContractAttributeEnum.STATE = Symbol('STATE'); ContractAttributeEnum.POSITION = Symbol('POSITION'); ContractAttributeEnum.EXTERNE = Symbol('EXTERNE'); ContractAttributeEnum.DESCRIPTION = Symbol('DESCRIPTION'); /** * Modified IdentityAttributeEnum - singular properties * * TODO: DRY, but how to generalize enum + static methods ... * * @author Radek Tomiška */ class IdentityAttributeEnum extends AbstractEnum { static getNiceLabel(key) { return super.getNiceLabel(`core:enums.IdentityAttributeEnum.${key}`); } static getHelpBlockLabel(key) { return super.getNiceLabel(`core:enums.IdentityAttributeEnum.helpBlock.${key}`); } static findKeyBySymbol(sym) { return super.findKeyBySymbol(this, sym); } static findSymbolByKey(key) { return super.findSymbolByKey(this, key); } static getField(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { case this.USERNAME: { return 'username'; } case this.EXTERNAL_CODE: { return 'externalCode'; } case this.DISABLED: { return 'disabled'; } case this.FIRSTNAME: { return 'firstName'; } case this.LASTNAME: { return 'lastName'; } case this.EMAIL: { return 'email'; } case this.PHONE: { return 'phone'; } case this.TITLE_BEFORE: { return 'titleBefore'; } case this.TITLE_AFTER: { return 'titleAfter'; } case this.DESCRIPTION: { return 'description'; } case this.FORM_PROJECTION: { return 'formProjection'; } default: { return null; } } } static getEnum(field) { if (!field) { return null; } switch (field) { case 'username': { return this.USERNAME; } case 'externalCode': { return this.EXTERNAL_CODE; } case 'disabled': { return this.DISABLED; } case 'firstName': { return this.FIRSTNAME; } case 'lastName': { return this.LASTNAME; } case 'email': { return this.EMAIL; } case 'phone': { return this.PHONE; } case 'titleBefore': { return this.TITLE_BEFORE; } case 'titleAfter': { return this.TITLE_AFTER; } case 'description': { return this.DESCRIPTION; } case 'formProjection': { return this.FORM_PROJECTION; } default: { return null; } } } static getLevel(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { default: { return 'default'; } } } } IdentityAttributeEnum.USERNAME = Symbol('USERNAME'); IdentityAttributeEnum.EXTERNAL_CODE = Symbol('EXTERNAL_CODE'); IdentityAttributeEnum.DISABLED = Symbol('DISABLED'); IdentityAttributeEnum.FIRSTNAME = Symbol('FIRSTNAME'); IdentityAttributeEnum.LASTNAME = Symbol('LASTNAME'); IdentityAttributeEnum.EMAIL = Symbol('EMAIL'); IdentityAttributeEnum.PHONE = Symbol('PHONE'); IdentityAttributeEnum.TITLE_BEFORE = Symbol('TITLE_BEFORE'); IdentityAttributeEnum.TITLE_AFTER = Symbol('TITLE_AFTER'); IdentityAttributeEnum.DESCRIPTION = Symbol('DESCRIPTION'); IdentityAttributeEnum.FORM_PROJECTION = Symbol('FORM_PROJECTION'); /** * Form attrribute select box. * * @author Radek Tomiška * @since 10.2.0 */ class AttributeOptionDecorator extends Basic.SelectBox.OptionDecorator { renderDescription(entity) { if (!entity || !entity._embedded || !entity._embedded.formDefinition) { return null; } // return ( <Basic.Div style={{ color: '#555', fontSize: '0.95em', fontStyle: 'italic' }}> { `${ this.i18n('entity.FormDefinition._type') }: ${ formDefinitionManager.getNiceLabel(entity._embedded.formDefinition, false) }` } </Basic.Div> ); } } /** * Detail rules of automatic role attribute * * @author Ondrej Kopr */ export default class AutomaticRoleAttributeRuleDetail extends Basic.AbstractContent { constructor(props, context) { super(props, context); this.manager = new AutomaticRoleAttributeRuleManager(); this.formAttributeManager = new FormAttributeManager(); this.state = { showLoading: false, typeForceSearchParameters: null, // force search parameters for EAV attribute // default type, show when create new entity type: AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY), valueRequired: true, // flag for required field formAttribute: null, // instance of form attribute, is used for computed field input attributeName: null, // name of identity attribute hideValueField: false, // Flag for hide attribute value intput incompatibleWithMultiple: false // Flag for check multivalued eavs and comparsion }; } getContentKey() { return 'content.automaticRoles.attribute'; } componentDidMount() { super.componentDidMount(); // const { entity } = this.props; this._initForm(entity); } // @Deprecated - since V10 ... replaced by dynamic key in Route // UNSAFE_componentWillReceiveProps(nextProps) { // // check id of old and new entity // if (nextProps.entity.id !== this.props.entity.id || nextProps.entity.attributeName !== this.props.entity.attributeName) { // this._initForm(nextProps.entity); // } // } getForm() { return this.refs.form; } getValue() { return this.refs.value; } isFormValid() { const { hideValueField } = this.state; // If valued is hidden (state property: hideValueField) isn't required validate value component return this.getForm().isFormValid() && (hideValueField || this.getValue().isValid()); } getCompiledData() { const formData = this.getForm().getData(); let value = this.getValue().getValue(); if (_.isObject(value)) { // eav form value value = this._getValueFromEav(value); } // attribute in backend is String type, we must explicit cast to string formData.value = String(value); // we must transform attribute name with case sensitive letters if (formData.attributeName) { if (formData.type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY)) { let attributeName = IdentityAttributeEnum.getField(IdentityAttributeEnum.findKeyBySymbol(formData.attributeName)); if (!attributeName) { attributeName = IdentityAttributeEnum.getField(formData.attributeName); } formData.attributeName = attributeName; } else { let attributeName = ContractAttributeEnum.getField(ContractAttributeEnum.findKeyBySymbol(formData.attributeName)); if (!attributeName) { attributeName = ContractAttributeEnum.getField(formData.attributeName); } formData.attributeName = attributeName; } } if (formData.type !== AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY_EAV) && formData.type !== AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.CONTRACT_EAV)) { formData.formAttribute = null; } const formAttribute = formData.formAttribute; if (formAttribute) { formData.formAttribute = formAttribute.id; if (!formData.attributeName) { formData.attributeName = formAttribute.code; } } return formData; } /** * Method for basic initial form */ _initForm(entity) { let attributeName = null; let hideValueField = false; if (entity !== undefined) { let formAttribute = null; if (!entity.id) { entity.type = AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY); entity.comparison = AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.EQUALS); attributeName = IdentityAttributeEnum.findKeyBySymbol(IdentityAttributeEnum.USERNAME); entity.attributeName = attributeName; } else if (entity.type !== AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY_EAV) && entity.type !== AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.CONTRACT_EAV)) { if (entity.type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY)) { entity.attributeName = IdentityAttributeEnum.getEnum(entity.attributeName); attributeName = IdentityAttributeEnum.findKeyBySymbol(entity.attributeName); } else { entity.attributeName = ContractAttributeEnum.getEnum(entity.attributeName); attributeName = ContractAttributeEnum.findKeyBySymbol(entity.attributeName); } } else if (entity._embedded && entity._embedded.formAttribute) { // eav is used formAttribute = entity._embedded.formAttribute; } if (entity.comparison === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_EMPTY) || entity.comparison === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_NOT_EMPTY)) { hideValueField = true; } this.setState({ typeForceSearchParameters: this._getForceSearchParametersForType(entity.type), type: entity.type, formAttribute, entity, attributeName, hideValueField }); this.refs.type.focus(); } } _getForceSearchParametersForType(type) { let typeForceSearchParameters = this.formAttributeManager.getDefaultSearchParameters().setFilter('confidential', false); if (type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY_EAV)) { typeForceSearchParameters = typeForceSearchParameters.setFilter(DEFINITION_TYPE_FILTER, IDENTITY_EAV_TYPE); } else if (type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.CONTRACT_EAV)) { typeForceSearchParameters = typeForceSearchParameters.setFilter(DEFINITION_TYPE_FILTER, CONTRACT_EAV_TYPE); } else { typeForceSearchParameters = null; } return typeForceSearchParameters; } /** * Get field form EAV, saved eav form value contains * value, seq and then value by persistent type for example: dateValue, doubleValue, ... */ _getValueFromEav(eav) { for (const field in eav) { if (field !== 'value' && field.includes('Value')) { return eav[field]; } } // return null; } _typeChange(option) { let typeForceSearchParameters = null; if (option) { typeForceSearchParameters = this._getForceSearchParametersForType(option.value); } // const { entity } = this.state; const newEntity = _.merge({}, entity); newEntity.type = option ? option.value : null; this.setState({ typeForceSearchParameters, type: option ? option.value : null, entity: newEntity, incompatibleWithMultiple: false }, () => { // clear values in specific fields this.refs.attributeName.setValue(null); this.refs.formAttribute.setValue(null); this.refs.comparison.setValue(AutomaticRoleAttributeRuleComparisonEnum.EQUALS); }); } _comparsionChange(option) { let valueRequired = true; let hideValueField = false; let incompatibleWithMultiple = true; if (option && ( option.value === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_EMPTY) || option.value === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_NOT_EMPTY))) { valueRequired = false; hideValueField = true; } if (option && ( option.value === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.EQUALS) || option.value === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_EMPTY) || option.value === AutomaticRoleAttributeRuleComparisonEnum.findKeyBySymbol(AutomaticRoleAttributeRuleComparisonEnum.IS_NOT_EMPTY))) { incompatibleWithMultiple = false; } // this.setState({ valueRequired, hideValueField, incompatibleWithMultiple }); } _formAttributeChange(option) { // just change formAttribute this.setState({ formAttribute: option }); } _attributeNameChange(option) { // set new attribute name this.setState({ attributeName: option ? option.value : null }); } /** * Return component that corespond with persisntent type of value type. * As default show text field. */ _getValueField(type, valueRequired, formAttribute, attributeName) { const { entity } = this.props; const value = entity.value; let finalComponent = null; // if (type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY) || type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.CONTRACT)) { finalComponent = this._getValueFieldForEntity(entity, type, value, attributeName, valueRequired); } else if (formAttribute) { finalComponent = this._getValueFieldForEav(formAttribute, value, valueRequired); } else { // form attribute doesn't exists finalComponent = this._getDefaultTextField(value, valueRequired); } return finalComponent; } _getValueFieldForEntity(entity, type, value, attributeName, valueRequired) { if (attributeName == null) { return this._getDefaultTextField(value, valueRequired); } // identity attributes if (type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY)) { // disabled is obly attribute that has different face if (IdentityAttributeEnum.findSymbolByKey(attributeName) === IdentityAttributeEnum.DISABLED) { return this._getDefaultBooleanSelectBox(value, valueRequired); } if (IdentityAttributeEnum.findSymbolByKey(attributeName) === IdentityAttributeEnum.FORM_PROJECTION) { return ( <Advanced.FormProjectionSelect ref="value" label={ this.i18n('entity.AutomaticRole.attribute.value.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.value.help') } value={ value } readOnly={ this.props.readOnly } required={ valueRequired } showIcon/> ); } return this._getDefaultTextField(value, valueRequired); } // contracts attributes // contract has externe and main as boolean and valid attributes as date if (ContractAttributeEnum.findSymbolByKey(attributeName) === ContractAttributeEnum.MAIN || ContractAttributeEnum.findSymbolByKey(attributeName) === ContractAttributeEnum.EXTERNE) { return this._getDefaultBooleanSelectBox(value, valueRequired); } if (ContractAttributeEnum.findSymbolByKey(attributeName) === ContractAttributeEnum.VALID_FROM || ContractAttributeEnum.findSymbolByKey(attributeName) === ContractAttributeEnum.VALID_TILL) { return this._getDefaultDateTimePicker(value, valueRequired); } if (ContractAttributeEnum.findSymbolByKey(attributeName) === ContractAttributeEnum.STATE) { return this._getContractStateEnum(value, valueRequired); } return this._getDefaultTextField(value, valueRequired); } _getValueFieldForEav(formAttribute, value, valueRequired) { const { readOnly } = this.props; const component = this.formAttributeManager.getFormComponent(formAttribute); if (!component || !component.component) { // when component doesn't exists show default field return this._getDefaultTextField(value, valueRequired); } if (formAttribute.persistentType === 'TEXT') { return ( <Basic.LabelWrapper label={ this.i18n('entity.AutomaticRole.attribute.value.label') }> <Basic.Alert text={this.i18n('attributeCantBeUsed.persistentTypeText', {name: formAttribute.name})}/> </Basic.LabelWrapper> ); } if (formAttribute.confidential) { return ( <Basic.LabelWrapper label={ this.i18n('entity.AutomaticRole.attribute.value.label') }> <Basic.Alert text={this.i18n('attributeCantBeUsed.confidential', {name: formAttribute.name})}/> </Basic.LabelWrapper> ); } const FormValueComponent = component.component; // // override helpBlock, label and placeholder const _formAttribute = _.merge({}, formAttribute); // immutable - form attribute is used twice on the form _formAttribute.description = this.i18n('entity.AutomaticRole.attribute.value.help'); _formAttribute.name = this.i18n('entity.AutomaticRole.attribute.value.label'); _formAttribute.placeholder = ''; _formAttribute.defaultValue = null; _formAttribute.required = valueRequired; _formAttribute.readonly = readOnly; // readnOnly from props has prio, default value is false _formAttribute.multiple = false; // Multiple value cannot be added // // is neccessary transform value to array return ( <FormValueComponent ref="value" attribute={ _formAttribute } readOnly={ readOnly } values={[{ value }]}/> ); } /** * Return simple text field for value input */ _getDefaultTextField(value, valueRequired) { const { readOnly } = this.props; // return ( <Basic.TextField ref="value" value={ value } readOnly={ readOnly } required={ valueRequired } label={ this.i18n('entity.AutomaticRole.attribute.value.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.value.help') }/> ); } /** * Return date time picker */ _getDefaultDateTimePicker(value, valueRequired) { const { readOnly } = this.props; // return ( <Basic.DateTimePicker ref="value" mode="date" readOnly={ readOnly } value={ value } required={ valueRequired } label={ this.i18n('entity.AutomaticRole.attribute.value.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.value.help') }/> ); } /** * Return default boolean select box */ _getDefaultBooleanSelectBox(value, valueRequired) { const { readOnly } = this.props; // return ( <Basic.BooleanSelectBox ref="value" value={ value } readOnly={ readOnly } required={ valueRequired } label={ this.i18n('entity.AutomaticRole.attribute.value.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.value.help') }/> ); } /** * Return simple text field for value input */ _getContractStateEnum(value, valueRequired) { const { readOnly } = this.props; // return ( <Basic.EnumSelectBox ref="value" value={ value } readOnly={ readOnly } required={ valueRequired } enum={ ContractStateEnum } useSymbol={ false } label={ this.i18n('entity.AutomaticRole.attribute.value.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.value.help') }/> ); } /** * Return warning for incompatible form attribute with comparsion */ _showIncompatibleWarning(show, formAttribute) { if (show && formAttribute) { return ( <Basic.Col lg={ 8 }> <Basic.LabelWrapper label={ this.i18n('entity.AutomaticRole.attribute.value.label') }> <Basic.Alert text={this.i18n('attributeCantBeUsed.multivaluedCantBeUsed', {name: formAttribute.name})}/> </Basic.LabelWrapper> </Basic.Col> ); } return null; } render() { const { uiKey, entity, readOnly} = this.props; const { typeForceSearchParameters, hideValueField, type, formAttribute, incompatibleWithMultiple, valueRequired, attributeName } = this.state; const incompatibleFinal = incompatibleWithMultiple && formAttribute && formAttribute.multiple; let data = this.state.entity; if (!data) { data = entity; } // return ( <Basic.Div> <Basic.AbstractForm ref="form" uiKey={ uiKey } data={ data } readOnly={ readOnly }> <Basic.EnumSelectBox ref="type" required clearable={ false } label={ this.i18n('entity.AutomaticRole.attribute.type.label') } helpBlock={ this.i18n('entity.AutomaticRole.attribute.type.help') } enum={ AutomaticRoleAttributeRuleTypeEnum } onChange={ this._typeChange.bind(this) }/> <Basic.EnumSelectBox ref="attributeName" clearable={ false } label={ this.i18n('entity.AutomaticRole.attribute.attributeName') } enum={ type === AutomaticRoleAttributeRuleTypeEnum.findKeyBySymbol(AutomaticRoleAttributeRuleTypeEnum.IDENTITY) ? IdentityAttributeEnum : ContractAttributeEnum } hidden={ typeForceSearchParameters !== null } onChange={ this._attributeNameChange.bind(this) } required={ !(typeForceSearchParameters !== null) }/> <Basic.SelectBox ref="formAttribute" clearable={ false } returnProperty={ null } onChange={ this._formAttributeChange.bind(this) } forceSearchParameters={ typeForceSearchParameters } label={ this.i18n('entity.AutomaticRole.attribute.formAttribute') } hidden={ typeForceSearchParameters === null } required={ !(typeForceSearchParameters === null) } manager={ this.formAttributeManager } niceLabel={ (attribute) => this.formAttributeManager.getNiceLabel(attribute, true) } optionComponent={ AttributeOptionDecorator }/> <Basic.Row> <Basic.Col lg={ hideValueField ? 12 : 4 }> <Basic.EnumSelectBox ref="comparison" clearable={ false } required useFirst onChange={ this._comparsionChange.bind(this) } label={ this.i18n('entity.AutomaticRole.attribute.comparison') } enum={ AutomaticRoleAttributeRuleComparisonEnum }/> </Basic.Col> { this._showIncompatibleWarning(incompatibleFinal, formAttribute) } <Basic.Col lg={ 8 } style={{ display: hideValueField || incompatibleFinal ? 'none' : '' }}> { this._getValueField(type, valueRequired, formAttribute, attributeName) } </Basic.Col> </Basic.Row> </Basic.AbstractForm> </Basic.Div> ); } } AutomaticRoleAttributeRuleDetail.propTypes = { entity: PropTypes.object, uiKey: PropTypes.string.isRequired, attributeId: PropTypes.string, readOnly: PropTypes.bool }; AutomaticRoleAttributeRuleDetail.defaultProps = { readOnly: false };
packages/react-server-examples/code-splitting/components/Header.js
redfin/react-server
import React from 'react'; import {logging} from 'react-server'; import PropTypes from "prop-types"; const logger = logging.getLogger(__LOGGER__); const Header = ({ headerText }) => { logger.info("rendering the header"); return ( <div className="header"> React-Server { headerText } </div> ); }; Header.propTypes = { headerText: PropTypes.string, }; export default Header
blueocean-material-icons/src/js/components/svg-icons/toggle/star-half.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ToggleStarHalf = (props) => ( <SvgIcon {...props}> <path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4V6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/> </SvgIcon> ); ToggleStarHalf.displayName = 'ToggleStarHalf'; ToggleStarHalf.muiName = 'SvgIcon'; export default ToggleStarHalf;
src/treemap/treemap-svg.js
Apercu/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import XYPlot from 'plot/xy-plot'; import PolygonSeries from 'plot/series/polygon-series'; import MarkSeries from 'plot/series/mark-series'; import LabelSeries from 'plot/series/label-series'; const MARGIN_ADJUST = 1.2; class TreemapSVG extends React.Component { getCircularNodes() { const { animation, nodes, onLeafMouseOver, onLeafMouseOut, onLeafClick, scales, style } = this.props; const {rows, minY, maxY, minX, maxX} = nodes.reduce((acc, node, index) => { const {x, y, r} = node; return { maxY: Math.max(y + r, acc.maxY), minY: Math.min(y - r, acc.minY), maxX: Math.max(x + MARGIN_ADJUST * r, acc.maxX), minX: Math.min(x - MARGIN_ADJUST * r, acc.minX), rows: acc.rows.concat([{ x, y, size: r, color: scales.color(node) }]) }; }, { rows: [], maxY: -Infinity, minY: Infinity, maxX: -Infinity, minX: Infinity }); return { updatedNodes: ( <MarkSeries animation={animation} className="rv-treemap__leaf rv-treemap__leaf--circle" onSeriesMouseEnter={onLeafMouseOver} onSeriesMouseLeave={onLeafMouseOut} onSeriesClick={onLeafClick} data={rows} colorType="literal" sizeType="literal" style={style}/> ), minY, maxY, minX, maxX }; } getNonCircularNodes() { const { animation, nodes, onLeafMouseOver, onLeafMouseOut, onLeafClick, scales, style } = this.props; const {color} = scales; return nodes.reduce((acc, node, index) => { if (!index) { return acc; } const {x0, x1, y1, y0} = node; const x = x0; const y = y0; const nodeHeight = y1 - y0; const nodeWidth = x1 - x0; acc.maxY = Math.max(y + nodeHeight, acc.maxY); acc.minY = Math.min(y, acc.minY); acc.maxX = Math.max(x + nodeWidth, acc.maxX); acc.minX = Math.min(x, acc.minX); const data = [ {x, y}, {x, y: y + nodeHeight}, {x: x + nodeWidth, y: y + nodeHeight}, {x: x + nodeWidth, y} ]; acc.updatedNodes = acc.updatedNodes.concat([ (<PolygonSeries animation={animation} className="rv-treemap__leaf" key={index} color={color(node)} type="literal" onSeriesMouseEnter={onLeafMouseOver} onSeriesMouseLeave={onLeafMouseOut} onSeriesClick={onLeafClick} data={data} style={{ ...style, ...node.style }} />) ]); return acc; }, { updatedNodes: [], maxY: -Infinity, minY: Infinity, maxX: -Infinity, minX: Infinity }); } render() { const { className, height, mode, nodes, width } = this.props; const useCirclePacking = mode === 'circlePack'; const {minY, maxY, minX, maxX, updatedNodes} = useCirclePacking ? this.getCircularNodes() : this.getNonCircularNodes(); const labels = nodes.reduce((acc, node) => { if (!node.data.title) { return acc; } return acc.concat({ ...node.data, x: node.x0 || node.x, y: node.y0 || node.y, label: `${node.data.title}` }); }, []); return ( <XYPlot className={`rv-treemap ${useCirclePacking ? 'rv-treemap-circle-packed' : ''} ${className}`} width={width} height={height} yDomain={[maxY, minY]} xDomain={[minX, maxX]} colorType="literal" {...this.props} > {updatedNodes} <LabelSeries data={labels} /> </XYPlot> ); } } TreemapSVG.displayName = 'TreemapSVG'; export default TreemapSVG;
src/commons/Button.js
zenria/react-redux-sandbox
import React from 'react'; const Button = ({ onClick, text, disabled})=> ( <input type="button" onClick={onClick} value={text} disabled={disabled}/> ) export default Button;
src/web/containers/NotFoundPage/index.js
lukemarsh/react-redux-boilerplate
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import messages from './messages'; import Button from 'web/components/Button'; export const NotFound = (props) => ( <article> <h1>{messages.header}</h1> <Button handleRoute={function redirect() { props.dispatch(push('/')); }} > {messages.homeButton} </Button> </article> ); NotFound.propTypes = { dispatch: React.PropTypes.func, }; // Wrap the component to inject dispatch and state into it export default connect()(NotFound);
src/components/webstorm/plain-wordmark/WebstormPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './WebstormPlainWordmark.svg' /** WebstormPlainWordmark */ function WebstormPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'WebstormPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } WebstormPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default WebstormPlainWordmark
src/react/comments.js
googlearchive/sample-framework-boot
/*! * * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-env es6 */ import React from 'react'; import VoteButtons from './vote-buttons'; export default class Comments extends React.Component { render () { const comments = this.props.comments; return ( <section className="post__comments"> <h1>Comments</h1> { comments.map((c, index) => { return ( <div className="post__comment" key={index}> <h2 className="post__comment-author">{c.username} wrote</h2> <p className="post__comment-text"> {c.text} </p> <VoteButtons score={c.score} /> </div> ); }) } </section> ); } }
src/svg-icons/action/info.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionInfo = (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 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/> </SvgIcon> ); ActionInfo = pure(ActionInfo); ActionInfo.displayName = 'ActionInfo'; ActionInfo.muiName = 'SvgIcon'; export default ActionInfo;
app/assets/scripts/components/modal-vote.js
openaq/openaq.github.io
'use strict'; import React from 'react'; import { connect } from 'react-redux'; import c from 'classnames'; import OpenAQ from 'openaq-design-system'; const { Modal, ModalHeader, ModalBody } = OpenAQ.Modal; var ModalVote = React.createClass({ displayName: 'ModalVote', propTypes: { onModalClose: React.PropTypes.func }, // // Render Methods // render: function () { return ( <Modal id='modal-vote' className='modal--medium' onCloseClick={this.props.onModalClose} revealed > <ModalHeader> <div className='modal__headline'> <h1 className='modal__title'>The Open Science Prize Vote ends on Friday, Jan 6! Have you voted?</h1> </div> </ModalHeader> <ModalBody> <div className='prose'> <p className='modal__description'>Hello, OpenAQ Community! We hope this find you well and building all kinds of cool stuff with open air quality data.</p> <p className='modal__description'>Sorry to bother you, but please consider voting in the <a href='https://www.openscienceprize.org/' target='_blank'>Open Science Prize</a> competition that we're a finalist in, along with several other awesome open science projects.</p> <p className='modal__description'>Your vote supports open data, open science and open-source work. This message will disappear after January 6th, when the competition closes.</p> <form className='form form-vote'> <div className='form__actions'> <button type='button' className='button button--primary-bounded' onClick={this.props.onModalClose}>Dismiss</button> <a href='http://event.capconcorp.com/wp/osp/vote-now/' onClick={this.props.onModalClose} className={c('button-modal-vote', {disabled: false})} target='_blank'>I'll Vote!</a> </div> </form> </div> </ModalBody> </Modal> ); } }); // /////////////////////////////////////////////////////////////////// // // Connect functions function selector (state) { return {}; } function dispatcher (dispatch) { return {}; } module.exports = connect(selector, dispatcher)(ModalVote);