path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
react-flux-mui/js/material-ui/src/svg-icons/editor/format-align-center.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatAlignCenter = (props) => ( <SvgIcon {...props}> <path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/> </SvgIcon> ); EditorFormatAlignCenter = pure(EditorFormatAlignCenter); EditorFormatAlignCenter.displayName = 'EditorFormatAlignCenter'; EditorFormatAlignCenter.muiName = 'SvgIcon'; export default EditorFormatAlignCenter;
src/common/SpellIcon.js
hasseboulen/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPELLS from './SPELLS'; import SpellLink from './SpellLink'; import Icon from './Icon'; const SpellIcon = ({ id, noLink, ...others }) => { if (process.env.NODE_ENV === 'development' && !SPELLS[id]) { throw new Error(`Unknown spell: ${id}`); } const spell = SPELLS[id] || { name: 'Spell not recognized', icon: 'inv_misc_questionmark', }; const icon = ( <Icon icon={spell.icon} alt={spell.name} {...others} /> ); if (noLink) { return icon; } return ( <SpellLink id={id}> {icon} </SpellLink> ); }; SpellIcon.propTypes = { id: PropTypes.number.isRequired, noLink: PropTypes.bool, }; export default SpellIcon;
examples/using-wordpress/src/components/styled/layout.js
okcoker/gatsby
import React from 'react'; import styled, { css } from 'styled-components'; import { compute, ifDefined } from '../../utils/hedron'; import * as PR from './propReceivers'; import { Page as HedronPage, Row as HedronRow, Column as HedronColumn } from 'hedron'; import theme from './theme'; const { sizes, color } = theme; /* * Media Queries * xs: < 450 * sm: < 692 * md: < 991 * lg: 992 and beyound */ // const media = { // tablet: (...args) => css` // @media (min-width: 420px) { // ${ css(...args) } // } // ` // } // Iterate through the sizes and create a media template export const media = Object.keys(sizes).reduce((acc, label) => { acc[label] = (...args) => css` @media (max-width: ${sizes[label] / 16}em) { ${css(...args)} } ` return acc }, {}) /* * Grid */ export const Page = styled(HedronPage)` ${props => props.fluid ? 'width: 100%;' : ` margin: 0 auto; max-width: 100%; ${props.width ? `width: ${props.width};` : `width: ${sizes.max};` } ` } `; export const RowHedron = styled(HedronRow)` display: flex; flex-direction: row; flex-wrap: wrap; ${ifDefined('alignContent', 'align-content')} ${ifDefined('alignItems', 'align-items')} ${ifDefined('alignSelf', 'align-self')} ${ifDefined('justifyContent', 'justify-content')} ${ifDefined('order')} `; export const gutter = props => css` padding-right: 40px; padding-left: 40px; ${media.sm` padding-right: 15px; padding-left: 15px; `} `; export const Row = styled(({ gutter, gutterWhite, height, borderBottom, borderTop, borderLeft, borderRight, outline, ...rest }) => <RowHedron {...rest}/> )` ${props => props.gutter && gutter }; ${props => css` background-color: ${props.gutterWhite ? color.white : color.lightGray}`}; ${PR.heightProps}; ${PR.borderProps}; ${PR.outlineProps}; `; export const Column = styled(({ outline, ...rest }) => <HedronColumn {...rest}/>)` display: block; ${props => props.debug ? `background-color: rgba(50, 50, 255, .1); outline: 1px solid #fff;` : '' } box-sizing: border-box; padding: 0; width: 100%; ${compute('xs')} ${compute('sm')} ${compute('md')} ${compute('lg')} ${PR.outlineProps} `;
components/Deck/TranslationPanel/TranslationPanel.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import {connectToStores} from 'fluxible-addons-react'; import {getLanguageName, getLanguageNativeName} from '../../../common'; import {NavLink, navigateAction} from 'fluxible-router'; import translateDeckRevision from '../../../actions/translateDeckRevision.js'; import { Dropdown, Menu, Button, Modal, Popup } from 'semantic-ui-react'; import TranslationStore from '../../../stores/TranslationStore'; import UserProfileStore from '../../../stores/UserProfileStore'; class TranslationPanel extends React.Component { handleLanguageClick(id){ this.context.executeAction(navigateAction, { url: '/deck/'+ id }); } // handleTranslateToClick(event,data){ // //$(document).find('#deckViewPanel').prepend('<div className="ui active dimmer"><div className="ui text loader">Loading</div></div>'); // this.context.executeAction(translateDeckRevision, { // // TODO this is wrong, the second part for a lanugage code is the COUNTRY not the language, so for greek the el_EL is invalid // language: data.value+'_'+data.value.toUpperCase() // }); // this.dropDown.setValue(''); // // // // // } renderAvailable(translation) { if (translation.language !== this.props.TranslationStore.currentLang.language){ let languageName = ''; if(translation.language){ languageName = getLanguageName(translation.language.toLowerCase().substr(0,2)); } if (languageName){ return ( <Dropdown.Item key = {translation.language} onClick={ this.handleLanguageClick.bind(this, translation.deck_id) } //href={''} > {languageName} </Dropdown.Item> ); } } } renderTranslateTo(supported) { return ( {value:supported.code , text: supported.name} ); } render() { let deckLanguage = ''; this.props.TranslationStore.currentLang ? deckLanguage = this.props.TranslationStore.currentLang.language : deckLanguage = 'Undefined'; //console.log(this.props.TranslationStore); let translations = []; let existing_codes = []; if (this.props.TranslationStore.translations){ translations = this.props.TranslationStore.translations; existing_codes = this.props.TranslationStore.translations.map((el) => { return el.language.split('_')[0]; }); } const supported = this.props.TranslationStore.supportedLangs.filter((el) => { return !existing_codes.includes(el.code); }); const user = this.props.UserProfileStore.userid; let divider = (user && translations.length) ? <Dropdown.Divider /> : ''; let languageOptions = supported.map(this.renderTranslateTo, this); // let translate_item = user ? // // <Dropdown text='Translate...' // floating // labeled // button // scrolling // className='icon primary small' // icon='world' // options={languageOptions} // onChange = {this.handleTranslateToClick.bind(this)} // ref = {(dropDown) => {this.dropDown = dropDown;}} // /> // // : ''; let currentLang = deckLanguage ? <span><i className='icon comments'/>{getLanguageName(deckLanguage.toLowerCase().substr(0,2))}</span> : <span>English</span>; return( <span> {translations.length ? ( <Dropdown item trigger={currentLang}> <Dropdown.Menu> { translations.map(this.renderAvailable, this) } </Dropdown.Menu> </Dropdown> ) : ( <span>{currentLang}</span> )} </span> ); } } TranslationPanel.contextTypes = { executeAction: PropTypes.func.isRequired }; TranslationPanel = connectToStores(TranslationPanel, [TranslationStore, UserProfileStore], (context, props) => { return { TranslationStore: context.getStore(TranslationStore).getState(), UserProfileStore: context.getStore(UserProfileStore).getState() }; }); export default TranslationPanel;
src/components/Form/Button.js
u-wave/web
import cx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import MuiButton from '@mui/material/Button'; function Button({ children, className, ...props }) { return ( <MuiButton variant="contained" color="primary" className={cx('Button', className)} type="submit" {...props} > {children} </MuiButton> ); } Button.propTypes = { className: PropTypes.string, children: PropTypes.node, }; export default Button;
src/components/sidebar/SidebarHeader.js
entria/entria-components
import React from 'react'; import { getTheme } from '../Theme'; const SidebarHeader = ({ children }) => <div style={styles().wrapper}> {children} </div>; const styles = () => ({ wrapper: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', height: 100, padding: 20, backgroundColor: getTheme().palette.primary1Color, color: 'white', boxSizing: 'border-box', }, }); export default SidebarHeader;
geonode/contrib/monitoring/frontend/src/components/cels/response-table/index.js
timlinux/geonode
import React from 'react'; import PropTypes from 'prop-types'; import HR from '../../atoms/hr'; import styles from './styles'; class ResponseTable extends React.Component { static propTypes = { average: PropTypes.number, errorNumber: PropTypes.number, max: PropTypes.number, requests: PropTypes.number, } render() { const average = this.props.average ? `${this.props.average} ms` : 'N/A'; const max = this.props.max ? `${this.props.max} ms` : 'N/A'; const requests = this.props.requests || 0; return ( <div style={styles.content}> <h4>Average Response Time {average}</h4> <HR /> <h4>Max Response Time {max}</h4> <HR /> <h4>Total Requests {requests}</h4> <HR /> <h4>Total Errors {this.props.errorNumber}</h4> </div> ); } } export default ResponseTable;
docs/examples/elements/Milestone.js
krebbl/react-svg-canvas
import React from 'react'; import Element from 'react-svg-canvas/Element'; import Text from 'react-svg-canvas/Text'; import Table from 'react-svg-canvas/Table'; import FontIcon from './FontIcon'; export default class Milestone extends Element { type = 'timeline-milestone'; isGroup = true; static defaultProps = Object.assign({}, Element.defaultProps, { selectable: true, rotate: 0, milestones: [], hoverOnBBox: false }); static childrenTypes = { milestones: Text, labelProps: Text, titleProps: Text, contentProps: Text, iconProps: FontIcon }; static defaultDataProps = { height: -260, milestones: [ { text: 'foo' }, { text: 'bar' } ], iconProps: { font: 'FontAwesome', icon: '\uf135' }, labelProps: { text: '2017', width: 100 }, titleProps: { text: 'My Title' }, contentProps: { text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dol' } }; processChange(key, value, trigger) { super.processChange(key, value, trigger); } renderKnobs() { const ret = super.renderKnobs(); ret.shift(); return ret; } handleSizeChange = (ref) => { const textHeight = ref.actualHeight(); if (this.state.textHeight !== textHeight) { this.setState({ textHeight }); } }; handleClick = () => { this.updateProp('labelProps', Object.assign({}, this.props.labelProps, {text: 'Hello World'})); this.dataChanged(); }; renderChildren() { const bigCircleRadius = 24; const smallCircleColor = this.props.color; const clipId = `milestoneClip_${this.props._id}`; return (<g ref={this.handleBBoxRef}> <g transform={`translate(0,${this.props.height + 10})`}> <Text {...this.props.labelProps} movable={false} scalable={false} textAlign="center" fontSize={12} x={-50} fill={smallCircleColor} onSizeChange={this.handleSizeChange} /> <g transform={`translate(0, ${this.state.textHeight || 12})`}> <line x1="0" x2="0" y1={10} y2={100 - bigCircleRadius + 10} stroke="gray" strokeWidth="1" /> <circle r={bigCircleRadius} stroke="gray" strokeWidth="1" cy={100 + 10} fill="transparent" /> <FontIcon {...this.props.iconProps} movable={false} y={100 + 10} size={26} fill={smallCircleColor} /> <line x1="0" x2="0" y1={100 + bigCircleRadius + 10} y2={-this.props.height - (this.state.textHeight || 12)} stroke="gray" strokeWidth="1" /> <circle r="4" fill="gray" cy={10} /> </g> </g> <circle r="13" fill="white" stroke="gray" strokeWidth="1" /> <circle fill={smallCircleColor} r="11" /> <Table y={this.props.height + (12 * 4) + 10} x={40} rowPadding={5}> <Text {...this.props.titleProps} maxWidth={200} movable={false} scalable={false} textAlign="left" fontSize={14} background={this.context.slide.background} /> <Text {...this.props.contentProps} maxWidth={200} movable={false} scalable={false} textAlign="left" fontSize={12} background={this.context.slide.background} /> </Table> </g>); } }
node_modules/react-bootstrap/es/Tooltip.js
nikhil-ahuja/Express-React
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
examples/js/others/mouse-event-table.js
rolandsusans/react-bootstrap-table
/* eslint no-console: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class MouseEventTable extends React.Component { render() { const options = { onMouseLeave: function() { console.log('mouse leave from table'); }, onMouseEnter: function() { console.log('mouse enter to table'); }, onRowMouseOut: function(row, e) { console.log(e); console.log('mouse leave from row ' + row.id); }, onRowMouseOver: function(row, e) { console.log(e); console.log('mouse enter from row ' + row.id); } }; return ( <BootstrapTable data={ products } options={ options }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
packages/material-ui-icons/src/CellWifiSharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M6 22h16V5.97L6 22z" /><path d="M18 9.98L6 22h12V9.98zM3.93 5.93l1.29 1.29c3.19-3.19 8.38-3.19 11.57 0l1.29-1.29c-3.91-3.91-10.25-3.91-14.15 0zm5.14 5.14L11 13l1.93-1.93c-1.07-1.06-2.79-1.06-3.86 0zM6.5 8.5l1.29 1.29c1.77-1.77 4.65-1.77 6.43 0L15.5 8.5c-2.48-2.48-6.52-2.48-9 0z" /></React.Fragment> , 'CellWifiSharp');
src/App.js
azaleas/game-of-live
import React, { Component } from 'react'; import _ from 'lodash'; import './App.css'; const medium = { boardSize: { width: 60, height: 40, }, boardResize: "medium", boardData: {}, cleanBoard: {}, iteratorCounter: 0, running: false, speed: 20, } const GameBoard = (props) => { const width = props.size.width; return( <div className="gameBoardWrapper" style={{width: width * 10 + "px"}} > { props.data.map((el, index) =>{ const rowIndex = index; return( <div key={"r=" + index} className="boardRow" > { el.map((el, index) => { return( <div key={"c=" + index} data-rowIndex={rowIndex} data-columnIndex={index} onClick={props.cellClick} className={"boardCell " + (el === 1 ? "live" : "dead")} > </div> ) }) } </div> ) }) } </div> ); } class App extends Component { constructor(props) { super(props); this.state = medium; } componentWillMount(){ this.dataFirst(this.state); } dataFirst = (data) =>{ let boardData = []; let boardRows = []; const height = data.boardSize.height; const width = data.boardSize.width; for (let h = 0; h < height; h++){ for (let w = 0; w < width; w++){ boardRows.push(0); if(w + 1 === width){ boardData.push(boardRows); boardRows = []; } } if(h+1 === height){ let cleanBoard = _.cloneDeep(boardData) boardData[2][4] = 1; boardData[3][5] = 1; boardData[4][3] = 1; boardData[4][4] = 1; boardData[4][5] = 1; boardData[6][4] = 1; boardData[6][5] = 1; boardData[6][3] = 1; boardData[5][4] = 1; boardData[4][5] = 1; let state = Object.assign({}, data, { boardData, iteratorCounter: data.iteratorCounter+1, cleanBoard, running: true, }); setTimeout(() => { this.setState(state); this.iterator(data.iteratorCounter, data.speed); }, 500); } } } dataIterate = () => { let height = this.state.boardSize.height; let width = this.state.boardSize.width; let currentData = _.cloneDeep(this.state.boardData); let mirrorData = _.cloneDeep(currentData); let alive = false; for (let h = 0; h < height; h++){ let above = h > 0 ? h-1 : height-1; let below = h < height-1 ? h+1 : 0; for (let w = 0; w < width; w++){ let totalNeighborCount = 0; let left = w > 0 ? w-1 : width-1; let right = w < width-1 ? w+1 : 0; let topLeftCell = currentData[above][left]; let topRightCell = currentData[above][right]; let topCenter = currentData[above][w]; let middleLeft = currentData[h][left]; let middleRight = currentData[h][right]; let bottomLeftCell = currentData[below][left]; let bottomRightCell = currentData[below][right]; let bottomCenter = currentData[below][w]; totalNeighborCount += topLeftCell; // top left totalNeighborCount += topCenter; // top center totalNeighborCount += topRightCell; // top right totalNeighborCount += middleLeft; // middle left totalNeighborCount += middleRight; // middle right totalNeighborCount += bottomLeftCell; // bottom left totalNeighborCount += bottomCenter; // bottom center totalNeighborCount += bottomRightCell; // bottom right if(currentData[h][w] === 0){ switch(totalNeighborCount){ case 3: mirrorData[h][w] = 1; alive = true; //cell is dead but has 3 neighbours => cell alive break; default: mirrorData[h][w] = 0; // leave cell dead if its already dead and doesnt have 3 neighbours } } else if(currentData[h][w] === 1){ switch(totalNeighborCount){ case 2: case 3: mirrorData[h][w] = 1; alive = true; // leave cell alive if neighbour count is >=2 or <=3 break; default: mirrorData[h][w] = 0; //if cell is alive but if neighbour count is <= 1 or >=4 => cell dead } } } if(h+1 === height){ if(alive){ let iteratorCounter = this.state.iteratorCounter; this.setState({ boardData: _.cloneDeep(mirrorData), iteratorCounter: iteratorCounter+1, }); this.iterator(this.state.iteratorCounter, this.state.speed); } else{ this.setState({ boardData: _.cloneDeep(mirrorData), iteratorCounter: 0, running: false, }); } } } } iterator = (iteratorCounter, speed) =>{ iteratorCounter = this.state.iteratorCounter; setTimeout(() => { if(this.state.running){ this.dataIterate(); } }, speed); } play = (event) => { if(!this.state.running){ this.setState({ running: true, }); this.iterator(); } } pause = (event) => { if(this.state.running){ this.setState({ running: false, }) } } clear = (event) => { this.setState({ running: false, boardData: _.cloneDeep(this.state.cleanBoard), iteratorCounter: 0, }); } boardResize = (event) => { let boardName = event.target.name; if(this.state.boardResize !== event.target.name){ this.setState({ running: false, boardData: {}, }); } if(boardName === "medium" && this.state.boardResize !== "medium"){ this.dataFirst(medium); } else if(boardName === "small" && this.state.boardResize !== "small"){ const boardSize = { width: 40, height: 20, }; const small = Object.assign({}, medium, { boardSize, boardResize: "small", speed: 50, running: true, }); this.dataFirst(small); } else if(boardName === "big" && this.state.boardResize !== "big"){ const boardSize = { width: 80, height: 60, }; const big = Object.assign({}, medium, { boardSize, boardResize: "big", speed: 15, running: true, }); this.dataFirst(big); } } cellClick = (event) => { let rowIndex = event.target.getAttribute('data-rowIndex'); let columnIndex = event.target.getAttribute('data-columnIndex'); let currentData = this.state.boardData; currentData[rowIndex][columnIndex] = 1; this.setState({ boardData: currentData, }); } render() { return ( <div className="App container"> <h1 className="bg-primary title">Game Of Life with React</h1> <div className="boardControls"> <div className="btn btn-success" onClick={this.play}>Play</div> <div className="btn btn-warning" onClick={this.pause}>Pause</div> <div className="btn btn-danger" onClick={this.clear}>Clear</div> </div> <p><strong>Generation: </strong>{this.state.iteratorCounter}</p> { (this.state.boardData.length) ? ( <GameBoard data={this.state.boardData} size={this.state.boardSize} cellClick={this.cellClick} /> ) : ( <p>Loading...</p> ) } <div className="boardControls"> <a className="btn btn-info" name="small" onClick={this.boardResize}>Small</a> <a className="btn btn-default" name="medium" onClick={this.boardResize}>Medium</a> <a className="btn btn-primary" name="big" onClick={this.boardResize}>Big</a> </div> </div> ); } } export default App;
blueocean-material-icons/src/js/components/svg-icons/av/volume-off.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvVolumeOff = (props) => ( <SvgIcon {...props}> <path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/> </SvgIcon> ); AvVolumeOff.displayName = 'AvVolumeOff'; AvVolumeOff.muiName = 'SvgIcon'; export default AvVolumeOff;
app/components/CategoriesList/CategoryCard.js
vlastoun/picture-uploader-crud
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardActions, CardTitle, CardText } from 'material-ui/Card'; import DeleteButton from './DeleteButton'; import EditButton from './EditButton'; const buttonStyle = { margin: '0.5em', }; const cardStyle = { marginTop: '1em', marginBottom: '1em', }; /* eslint-disable react/prefer-stateless-function */ /* eslint-disable react/jsx-boolean-value */ class CategoryCard extends React.Component { constructor() { super(); this.state = { edit: false, shadow: 1 }; this.onMouseOut = this.onMouseOut.bind(this); this.onMouseOut = this.onMouseOut.bind(this); } onMouseOver = () => { this.setState({ shadow: 3 }); } onMouseOut = () => { this.setState({ shadow: 1 }); } render() { const { item } = this.props; return ( <Card style={cardStyle} zDepth={this.state.shadow} onMouseOver={this.onMouseOver} onFocus={this.onMouseOver} onMouseOut={this.onMouseOut} onBlur={this.onMouseOut} > <CardTitle title={item.name} actAsExpander={true} showExpandableButton={true} /> <CardText expandable={true}> {item.description} </CardText> <CardActions expandable={true}> <EditButton style={buttonStyle} edit={this.props.edit} post={item}> Edit </EditButton> <DeleteButton style={buttonStyle} delete={this.props.delete} post={item} /> </CardActions> </Card> ); } } CategoryCard.propTypes = { delete: PropTypes.func.isRequired, edit: PropTypes.func.isRequired, item: PropTypes.object.isRequired, }; export default CategoryCard;
es6/Radio/RadioButton.js
yurizhang/ishow
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; //import {default as Component} from '../../plugs/index.js'; //提供style, classname方法 import '../Common/css/radio-button.css'; import Radio from './Radio'; var RadioButton = function (_Radio) { _inherits(RadioButton, _Radio); function RadioButton() { _classCallCheck(this, RadioButton); return _possibleConstructorReturn(this, (RadioButton.__proto__ || Object.getPrototypeOf(RadioButton)).apply(this, arguments)); } _createClass(RadioButton, [{ key: 'parent', value: function parent() { return this.context.component; } }, { key: 'size', value: function size() { return this.parent().props.size; } }, { key: 'isDisabled', value: function isDisabled() { return this.props.disabled || this.parent().props.disabled; } }, { key: 'activeStyle', value: function activeStyle() { return { backgroundColor: this.parent().props.fill || '', borderColor: this.parent().props.fill || '', color: this.parent().props.textColor || '' }; } }, { key: 'render', value: function render() { return React.createElement( 'label', { style: this.style(), className: this.className('ishow-radio-button', this.props.size && 'ishow-radio-button--' + this.size(), { 'is-active': this.state.checked }) }, React.createElement('input', { type: 'radio', className: 'ishow-radio-button__orig-radio', checked: this.state.checked, disabled: this.isDisabled(), onChange: this.onChange.bind(this) }), React.createElement( 'span', { className: 'ishow-radio-button__inner', style: this.state.checked ? this.activeStyle() : {} }, this.props.children || this.props.value ) ); } }]); return RadioButton; }(Radio); RadioButton.elementType = 'RadioButton'; export default RadioButton; RadioButton.contextTypes = { component: PropTypes.any }; RadioButton.propTypes = { value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), disabled: PropTypes.bool, name: PropTypes.string };
linksa/YTjinfo.js
liuhui219/linksa
import React from 'react'; import { View, StyleSheet, Navigator, TouchableOpacity, TouchableHighlight, Text, ScrollView, ActivityIndicator, InteractionManager, Dimensions, BackAndroid, Image, RefreshControl, ListView, } from 'react-native'; import ScrollableTabView, { DefaultTabBar, } from 'react-native-scrollable-tab-view'; import Token from './Token'; import Icon from 'react-native-vector-icons/Ionicons'; import YTjinfoa from './YTjinfoa'; var array = []; export default class YTjinfo extends React.Component { constructor(props) { super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), id: '', uid:'', datas:[], imgs:[], loaded: false, isLoadMore:false, p:1, isReach:false, isRefreshing:false, isNull:false, sx:false, datda:null, }; } componentDidMount() { //这里获取传递过来的参数: name array = []; aa=[]; this.setState({datda:data.data.domain}) this.timer = setTimeout( () => {this.fetchData('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '&p='+this.state.p);},800); } componentWillUnmount() { this.timer && clearTimeout(this.timer); } fetchData(url) { var that=this; fetch(url) .then((response) => response.json()) .then((responseData)=>{ if(responseData.data.data != ''){ responseData.data.data.forEach((Data,i) => { key={i} array.push(Data); }) } if(responseData.data.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(responseData.data.count == 0){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isNull:true, }) }else if(array.length > responseData.data.count){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isNull:false, }) } console.log(responseData) }) .catch((error) => { that.setState({ loaded: true, sx:true, isReach:true, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } infos(data){ const { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { this.props.navigator.push({ name: 'YTjinfoa', component: YTjinfoa, params: { data: data, imgs: {uri: this.state.datda.slice(0,-6)+data.img.slice(1)} } }) }) } } render() { if(!this.state.loaded){ return ( <View style={{justifyContent: 'center',alignItems: 'center',height:Dimensions.get('window').height-90,}}> <View style={styles.loading}> <ActivityIndicator color="white"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.loadingTitle}>加载中……</Text> </View> </View> ) } return( <ListView dataSource={this.state.dataSource} renderRow={this.renderMovie.bind(this)} onEndReached={this._onEndReach.bind(this) } onEndReachedThreshold={2} renderFooter={this._renderFooter.bind(this)} refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh.bind(this) } colors={['#ff0000', '#00ff00', '#0000ff','#3ad564']} progressBackgroundColor="#ffffff" /> } /> ) } _ggButton(id){ const { navigator } = this.props; if(navigator) { InteractionManager.runAfterInteractions(() => { this.props.navigator.push({ name: 'Gonggaob', component: Gonggaob, params: { id: id, } }) }) } } renderMovie(data,sectionID: number, rowID: number) { if(this.state.sx){ return( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-sad-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else if(this.state.isNull){ return ( <View style={{justifyContent:'center',alignItems:'center',height:Dimensions.get('window').height-170,}}> <Icon name="ios-folder-outline" color="#ccc"size={70} /> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:18,}}>{data}</Text> </View> ) } else{ return ( <View style={{paddingBottom:15, justifyContent:'center',alignItems:'center', backgroundColor:'#fff',borderBottomWidth:1, borderColor:'#eee'}}> <TouchableOpacity activeOpacity={0.8} onPress={this.infos.bind(this,data)} style={{justifyContent:'center',alignItems:'center', }}> <View style={{flexDirection:'row',paddingTop:15,}}> <View style={{marginLeft:15,marginRight:15,width: 40, height: 40,borderRadius:20,backgroundColor:'#ccc',alignItems:'center', justifyContent:'center'}}> <Image source={require('./imgs/ren.png')} style={{width: 20, height: 20, }} /> </View> <View style={{flex:1,flexDirection:'column',}}> <View style={{flexDirection:'row',justifyContent:'space-between'}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:14,}}>{data.userid}</Text> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{color:'#999',paddingRight:15,}}>{data.time}</Text> </View> <View style={{ borderRadius:3,}}> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{flexWrap:'wrap',marginTop:5,fontSize:14, paddingRight:15,}}>{data.address}</Text> </View> </View> </View> </TouchableOpacity> </View> ) } } _renderFooter() { if(this.state.isLoadMore){ return ( <View style={styles.footer}> <ActivityIndicator color="#4385f4"/> <Text allowFontScaling={false} adjustsFontSizeToFit={false} style={styles.footerTitle}>正在加载更多……</Text> </View> ) } } // 下拉刷新 _onRefresh() { this.setState({ isRefreshing:true, isReach:false, isLoadMore:false, p:1, }) var that=this fetch('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '') .then((response) => response.json()) .then(function (result) { array=[]; array.length = 0; if(result.data.data != ''){ result.data.data.forEach((Data,i) => { key={i} array.push(Data); }) } if(result.data.count <= 10){ that.setState({ isReach:true, isLoadMore:false, }) } if(result.data.count == 0){ that.setState({ dataSource: that.state.dataSource.cloneWithRows(['暂无数据']), loaded: true, sx:false, isLoadMore:false, isRefreshing:false, isReach:true, isNull:true, }) }else if(array.length > result.data.count){ that.setState({ isReach:true, isLoadMore:false, isNull:false, }) }else{ that.setState({ dataSource: that.state.dataSource.cloneWithRows(array), loaded: true, sx:false, isRefreshing:false, isNull:false, }) } console.log(result) }) .catch((error) => { that.setState({ loaded: true, sx:true, isReach:true, isRefreshing:false, dataSource: that.state.dataSource.cloneWithRows(['加载失败,请下拉刷新']), }) }); } _onEndReach() { if(!this.state.isReach){ this.setState({ isLoadMore:true, p:this.state.p+1, }) InteractionManager.runAfterInteractions(() => { this.fetchData('' + data.data.domain + '/index.php?app=Legwork&m=MLegwork&a=lists&sta=1&num=15&access_token=' + data.data.token + '&p='+this.state.p); }) } } } const styles = StyleSheet.create({ tabView: { flex: 1, flexDirection: 'column', backgroundColor:'#fafafa', }, card: { height:45, backgroundColor:'#4385f4', flexDirection:'row' }, loading: { backgroundColor: 'gray', height: 80, width: 100, borderRadius: 10, justifyContent: 'center', alignItems: 'center', }, loadingTitle: { marginTop: 10, fontSize: 14, color: 'white' }, footer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 40, }, footerTitle: { marginLeft: 10, fontSize: 15, color: 'gray' }, default: { height: 37, borderWidth: 0, borderColor: 'rgba(0,0,0,0.55)', flex: 1, fontSize: 13, }, });
web_src/src/components/App.js
salgum1114/sgoh-blog
import React from 'react'; class App extends React.Component { render(){ return ( <div> <h1>SpringBoot ReactJS Start!!</h1> <h2>SpringBoot ReactJS Start!!</h2> <h3>SpringBoot ReactJS Start!!</h3> </div> ); } } export default App;
src/CollapsibleMixin.js
jontewks/react-bootstrap
import React from 'react'; import TransitionEvents from './utils/TransitionEvents'; import deprecationWarning from './utils/deprecationWarning'; const CollapsibleMixin = { propTypes: { defaultExpanded: React.PropTypes.bool, expanded: React.PropTypes.bool }, getInitialState() { const defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : !!this.props.expanded; return { expanded: defaultExpanded, collapsing: false }; }, componentWillMount() { deprecationWarning('CollapsibleMixin', 'Collapse Component'); }, componentWillUpdate(nextProps, nextState) { let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded; if (willExpanded === this.isExpanded()) { return; } // if the expanded state is being toggled, ensure node has a dimension value // this is needed for the animation to work and needs to be set before // the collapsing class is applied (after collapsing is applied the in class // is removed and the node's dimension will be wrong) let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = '0'; if (!willExpanded) { value = this.getCollapsibleDimensionValue(); } node.style[dimension] = value + 'px'; this._afterWillUpdate(); }, componentDidUpdate(prevProps, prevState) { // check if expanded is being toggled; if so, set collapsing this._checkToggleCollapsing(prevProps, prevState); // check if collapsing was turned on; if so, start animation this._checkStartAnimation(); }, // helps enable test stubs _afterWillUpdate() { }, _checkStartAnimation() { if (!this.state.collapsing) { return; } let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let value = this.getCollapsibleDimensionValue(); // setting the dimension here starts the transition animation let result; if (this.isExpanded()) { result = value + 'px'; } else { result = '0px'; } node.style[dimension] = result; }, _checkToggleCollapsing(prevProps, prevState) { let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded; let isExpanded = this.isExpanded(); if (wasExpanded !== isExpanded) { if (wasExpanded) { this._handleCollapse(); } else { this._handleExpand(); } } }, _handleExpand() { let node = this.getCollapsibleDOMNode(); let dimension = this.dimension(); let complete = () => { this._removeEndEventListener(node, complete); // remove dimension value - this ensures the collapsible item can grow // in dimension after initial display (such as an image loading) node.style[dimension] = ''; this.setState({ collapsing:false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, _handleCollapse() { let node = this.getCollapsibleDOMNode(); let complete = () => { this._removeEndEventListener(node, complete); this.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, // helps enable test stubs _addEndEventListener(node, complete) { TransitionEvents.addEndEventListener(node, complete); }, // helps enable test stubs _removeEndEventListener(node, complete) { TransitionEvents.removeEndEventListener(node, complete); }, dimension() { return (typeof this.getCollapsibleDimension === 'function') ? this.getCollapsibleDimension() : 'height'; }, isExpanded() { return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, getCollapsibleClassSet(className) { let classes = {}; if (typeof className === 'string') { className.split(' ').forEach(subClasses => { if (subClasses) { classes[subClasses] = true; } }); } classes.collapsing = this.state.collapsing; classes.collapse = !this.state.collapsing; classes.in = this.isExpanded() && !this.state.collapsing; return classes; } }; export default CollapsibleMixin;
demos/forms-demo/src/components/Menu/SettingsCheckbox.js
bdjnk/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state, props, signal} from 'cerebral/tags' export default connect({ 'field': state`${props`path`}`, 'toggleSelectSettings': signal`app.toggleSelectSettings` }, function SettingsCheckbox ({field, path, toggleSelectSettings}) { const {value} = field return ( <div style={{float: 'left', paddingRight: 10, marginTop: 5}}> <input type={'checkbox'} checked={value ? 'checked' : ''} onChange={(e) => toggleSelectSettings({ field: path, value: !value })} /> {field.description} </div> ) } )
src/renderer/components/channel-switcher.js
r7kamura/retro-twitter-client
import List from './list'; import React from 'react'; import viewEventPublisher from '../singletons/view-event-publisher' export default class ChannelSwitcher extends React.Component { getHomeChannelClassName() { return `account-channel ${this.getHomeChannelSelected() ? ' account-channel-selected' : ''}`; } getHomeChannelSelected() { return this.props.channelId === 'HOME_TIMELINE_CHANNEL'; } getSearchChannelClassName() { return `account-channel ${this.getSearchChannelSelected() ? ' account-channel-selected' : ''}`; } getSearchChannelSelected() { return this.props.channelId === 'SEARCH_CHANNEL'; } onHomeChannelClicked(event) { viewEventPublisher.emit('channel-clicked', 'HOME_TIMELINE_CHANNEL'); } onSearchChannelClicked(event) { viewEventPublisher.emit('channel-clicked', 'SEARCH_CHANNEL'); } render() { return( <div className="channel-switcher"> <div className="account-screen-name"> @{this.props.account.screen_name} </div> <div className="account-section"> <h3 className="account-section-heading"> TIMELINES </h3> <ul> <li className={this.getHomeChannelClassName()} onClick={this.onHomeChannelClicked.bind(this)}> Home </li> <li className={this.getSearchChannelClassName()} onClick={this.onSearchChannelClicked.bind(this)}> Search </li> </ul> </div> <div className="account-section"> <h3 className="account-section-heading"> LISTS </h3> <ul> {this.renderLists()} </ul> </div> </div> ); } renderLists() { return this.props.lists.map((list) => { return <List channelId={this.props.channelId} key={list.id_str} list={list} />; }); } }
src/routes.js
IntellectionStudio/intellection.kz
import {PageContainer as PhenomicPageContainer} from 'phenomic'; import {Route} from 'react-router'; import React from 'react'; import AboutPage from 'layouts/AboutPage'; import ContactPage from 'layouts/ContactPage'; import CoursesPage from 'layouts/CoursesPage'; import ErrorPage from 'layouts/ErrorPage'; import HomePage from 'layouts/HomePage'; import KnowledgePage from 'layouts/KnowledgePage'; import Page from 'layouts/Page'; import StartupsPage from 'layouts/StartupsPage'; import ServicesPage from 'layouts/ServicesPage'; import TopicPage from 'layouts/TopicPage'; import AppContainer from './AppContainer'; const PageContainer = props => ( <PhenomicPageContainer {...props} layouts={{ AboutPage, ContactPage, CoursesPage, ErrorPage, HomePage, KnowledgePage, Page, StartupsPage, ServicesPage, TopicPage, }} /> ); const Routes = ( <Route component={AppContainer}> <Route path="*" component={PageContainer} /> </Route> ); export default Routes;
react/Regular/Regular.js
seekinternational/seek-asia-style-guide
import styles from './Regular.less'; import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export default function Regular({ children, className, ...restProps }) { return ( <span {...restProps} className={classnames(styles.root, className)}> {children} </span> ); } Regular.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string };
src/components/templates/content_body.js
hisarkaya/polinsur
import React from 'react'; const ContentBody = props => { return ( <div className="widget-content nopadding"> {props.children} </div> ); } export default ContentBody;
Rosa_Madeira/Cliente/src/components/catalogo/CatalogoLista.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, ListView, RefreshControl, ScrollView } from 'react-native'; import { Container, Content, Card, CardItem, Text, Button, Icon } from 'native-base'; import { connect } from 'react-redux'; import { fetch_catalogo } from '../../actions'; import CatalogoItem from './CatalogoItem'; import { Actions } from 'react-native-router-flux'; class CatalogoLista extends Component { componentWillMount() { this.props.fetch_catalogo(); this.createDataSource(this.props) // const { carrinhoLista } = this.props; // console.log(this.props); Actions.refresh({rightTitle: 'Carrinho', onRight: () => Actions.carrinho({type:'reset', listCarrinho: this.props.carrinhoLista}), rightButtonTextStyle: { color:'white'} }); } componentWillReceiveProps(nextProps){ this.createDataSource(nextProps) } createDataSource({listCatalogo}) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(listCatalogo); } renderRow(listCatalogo) { return <CatalogoItem catalogoLista={listCatalogo} /> } _onRefresh(){ setTimeout(() => { this.props.fetch_catalogo(); }, 1000); } render(){ return( <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} style={{marginTop: 70}} /> ); } } const mapStateToProps = state => { const listCatalogo = _.map(state.catalogo.catalogoLista, (key, value) => { return { ...key, value }; }); const { refreshing } = state.catalogo; const { carrinhoLista } = state.carrinho; return { listCatalogo, refreshing, carrinhoLista }; } export default connect(mapStateToProps, {fetch_catalogo})(CatalogoLista);
src/Parser/MistweaverMonk/Modules/Items/PetrichorLagniappe.js
mwwscott0/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import { formatNumber } from 'common/format'; import Combatants from 'Parser/Core/Modules/Combatants'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; import Module from 'Parser/Core/Module'; const debug = false; const PETRICHOR_REDUCTION = 2000; class PetrichorLagniappe extends Module { static dependencies = { combatants: Combatants, abilityTracker: AbilityTracker, }; REVIVAL_BASE_COOLDOWN = 0; totalReductionTime = 0; currentReductionTime = 0; wastedReductionTime = 0; initialWastedReductionTime = 0; casts = 0; lastCastTime = 0; cdReductionUsed = 0; on_initialized() { this.active = this.combatants.selected.hasWrists(ITEMS.PETRICHOR_LAGNIAPPE.id); if (this.active) { this.REVIVAL_BASE_COOLDOWN = 180000 - (this.combatants.selected.traitsBySpellId[SPELLS.TENDRILS_OF_REVIVAL.id] || 0) * 10000; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.REVIVAL.id) { if (this.casts !== 0) { debug && console.log('Time since last Revival cast: ', (event.timestamp - this.lastCastTime), ' //// Revival CD: ', this.REVIVAL_BASE_COOLDOWN); if ((event.timestamp - this.lastCastTime) < this.REVIVAL_BASE_COOLDOWN) { this.cdReductionUsed += 1; } this.wastedReductionTime += (event.timestamp - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime); this.lastCastTime = event.timestamp; this.currentReductionTime = 0; } // Tracking initial Revival cast - Any REM casts before this are considered wasted. if (this.casts === 0) { this.wastedReductionTime += this.currentReductionTime; this.initialWastedReductionTime = this.currentReductionTime; this.casts += 1; this.lastCastTime = event.timestamp; this.currentReductionTime = 0; } } if (spellId === SPELLS.RENEWING_MIST.id) { this.totalReductionTime += PETRICHOR_REDUCTION; this.currentReductionTime += PETRICHOR_REDUCTION; } } on_finished() { if (((this.owner.fight.end_time - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime)) > 0) { this.wastedReductionTime += (this.owner.fight.end_time - this.lastCastTime) - (this.REVIVAL_BASE_COOLDOWN - this.currentReductionTime); } if (debug) { console.log('Time Reduction: ', this.totalReductionTime); console.log('Wasted Reduction:', this.wastedReductionTime); } } item() { const abilityTracker = this.abilityTracker; const getAbility = spellId => abilityTracker.getAbility(spellId); return { item: ITEMS.PETRICHOR_LAGNIAPPE, result: ( <dfn data-tip={`The wasted cooldown reduction from the legendary bracers. ${formatNumber((this.wastedReductionTime / getAbility(SPELLS.REVIVAL.id).casts) / 1000)} seconds (Average wasted cooldown reduction per cast).`}> {formatNumber(this.wastedReductionTime / 1000)} seconds wasted </dfn> ), }; } } export default PetrichorLagniappe;
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/PropsConstructorNoArgs.js
facebook/flow
// @flow import React from 'react'; class MyComponent extends React.Component { constructor() {} defaultProps: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { constructor() {} defaultProps: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
src/backward/Widgets/Subtitle.js
chaitanya0bhagvan/NativeBase
/* @flow */ import React, { Component } from 'react'; import { Text } from 'react-native'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames'; class Subtitle extends Component { render() { return ( <Text ref={c => this._root = c} {...this.props} /> ); } } Subtitle.propTypes = { ...Text.propTypes, style: React.PropTypes.object, }; const StyledSubtitle = connectStyle('NativeBase.Subtitle', {}, mapPropsToStyleNames)(Subtitle); export { StyledSubtitle as Subtitle, };
node_modules/semantic-ui-react/dist/es/views/Feed/FeedLike.js
mowbell/clickdelivery-fed-test
import _extends from 'babel-runtime/helpers/extends'; import _isNil from 'lodash/isNil'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; import Icon from '../../elements/Icon'; /** * A feed can contain a like element. */ function FeedLike(props) { var children = props.children, className = props.className, content = props.content, icon = props.icon; var classes = cx('like', className); var rest = getUnhandledProps(FeedLike, props); var ElementType = getElementType(FeedLike, props); if (!_isNil(children)) { return React.createElement( ElementType, _extends({}, rest, { className: classes }), children ); } return React.createElement( ElementType, _extends({}, rest, { className: classes }), Icon.create(icon), content ); } FeedLike.handledProps = ['as', 'children', 'className', 'content', 'icon']; FeedLike._meta = { name: 'FeedLike', parent: 'Feed', type: META.TYPES.VIEW }; FeedLike.defaultProps = { as: 'a' }; process.env.NODE_ENV !== "production" ? FeedLike.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Shorthand for icon. Mutually exclusive with children. */ icon: customPropTypes.itemShorthand } : void 0; export default FeedLike;
client/routes.js
bbviana/alexandria-mern
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './modules/app/components/App'; import RecipeListPage from './modules/recipe/pages/RecipeListPage' // require.ensure polyfill for node if (typeof require.ensure !== 'function') { require.ensure = function requireModule(deps, callback) { callback(require); }; } /* Workaround for async react routes to work with react-hot-reloader till https://github.com/reactjs/react-router/issues/2182 and https://github.com/gaearon/react-hot-loader/issues/288 is fixed. */ if (process.env.NODE_ENV !== 'production') { // Require async routes only in development for react-hot-reloader to work. // require('./modules/recipe/pages/RecipeCreatePage'); require('./modules/recipe/pages/RecipeListPage'); } // react-router setup with code-splitting // More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/ export default ( <Route path="/" component={App}> <IndexRoute component={RecipeListPage} /> <Route path="/recipes" component={RecipeListPage}/> </Route> );
src/components/RemoveSectionButton.js
BenGoldstein88/redux-chartmaker
import React from 'react'; export default class RemoveSectionButton extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { e.preventDefault() this.props.removeSection(this.props.id); } render() { return ( <div style={{ display: 'inline-block' }}> <button className={'remove-section-button'}onClick={this.handleClick} > <p style={{ position: 'absolute', top: '20%', left: '52%', width: '100%', transform: 'translate(-50%, -50%)' }}>REMOVE SECTION</p> </button> </div> ); } }
src/images/Icons/instagram.js
sourabh-garg/react-starter-kit
import React from 'react'; export default function instagram(props) { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enableBackground="new 0 0 64 64" xmlSpace="preserve" {...props}> <g transform="translate(0, 0)"> <path fill="#444444" d="M32,5.766c8.544,0,9.556,0.033,12.931,0.187c3.642,0.166,7.021,0.895,9.621,3.496 c2.6,2.6,3.329,5.979,3.496,9.621c0.154,3.374,0.187,4.386,0.187,12.931s-0.033,9.556-0.187,12.931 c-0.166,3.642-0.895,7.021-3.496,9.621c-2.6,2.6-5.98,3.329-9.621,3.496c-3.374,0.154-4.386,0.187-12.931,0.187 s-9.557-0.033-12.931-0.187c-3.642-0.166-7.021-0.895-9.621-3.496c-2.6-2.6-3.329-5.979-3.496-9.621 C5.798,41.556,5.766,40.544,5.766,32s0.033-9.556,0.187-12.931c0.166-3.642,0.895-7.021,3.496-9.621 c2.6-2.6,5.979-3.329,9.621-3.496C22.444,5.798,23.456,5.766,32,5.766 M32,0c-8.691,0-9.78,0.037-13.194,0.193 c-5.2,0.237-9.768,1.511-13.436,5.178C1.705,9.037,0.43,13.604,0.193,18.806C0.037,22.22,0,23.309,0,32 c0,8.691,0.037,9.78,0.193,13.194c0.237,5.2,1.511,9.768,5.178,13.436c3.666,3.666,8.234,4.941,13.436,5.178 C22.22,63.963,23.309,64,32,64s9.78-0.037,13.194-0.193c5.199-0.237,9.768-1.511,13.436-5.178c3.666-3.666,4.941-8.234,5.178-13.436 C63.963,41.78,64,40.691,64,32s-0.037-9.78-0.193-13.194c-0.237-5.2-1.511-9.768-5.178-13.436 c-3.666-3.666-8.234-4.941-13.436-5.178C41.78,0.037,40.691,0,32,0L32,0z" /> <path data-color="color-2" fill="#444444" d="M32,15.568c-9.075,0-16.432,7.357-16.432,16.432c0,9.075,7.357,16.432,16.432,16.432 S48.432,41.075,48.432,32C48.432,22.925,41.075,15.568,32,15.568z M32,42.667c-5.891,0-10.667-4.776-10.667-10.667 c0-5.891,4.776-10.667,10.667-10.667c5.891,0,10.667,4.776,10.667,10.667C42.667,37.891,37.891,42.667,32,42.667z" /> <circle data-color="color-2" fill="#444444" cx="49.082" cy="14.918" r="3.84" /> </g> </svg> ); }
src/svg-icons/image/crop-din.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropDin = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/> </SvgIcon> ); ImageCropDin = pure(ImageCropDin); ImageCropDin.displayName = 'ImageCropDin'; ImageCropDin.muiName = 'SvgIcon'; export default ImageCropDin;
HotelAndroid/thanksALot.js
MJ111/hotel-reverse
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, DatePickerAndroid, TouchableWithoutFeedback, Picker, Navigator, } from 'react-native'; const Item = Picker.Item; import Button from 'react-native-button'; /*---------------------------------------------------------------- Structure Header: Your Wish List Body: Bidding Info Footer: <Are you sure?> <No, I'm not sure!> buttons ----------------------------------------------------------------*/ class ThanksALot extends Component { constructor(props) { super(props); console.log('thnaxk'); } _handlePress(where) { this.props.navigator.push({id: where}); // console.log('nav: ', this.props.navigator); } render() { return ( <View style={{flex: 1}}> <Text style={styles.appName}> 이용해 주셔서 감사합니다!!! </Text> <View style={styles.rowContainer}> <Button style={styles.searchBtnText} containerStyle={styles.searchBtn} onPress={() => this._handlePress('search')}> HOME </Button> </View> </View> ); } } const styles = StyleSheet.create({ rowContainer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', margin: 10, }, smallRowContainer: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-start', marginLeft: 30, marginTop: 2, marginBottom: 2 }, appName: { fontSize: 20, textAlign: 'center', color: '#000', margin: 10, }, label: { width: 60, textAlign: 'left', margin: 10, color: 'black', }, searchBtn: { width: 150, padding:10, height: 30, overflow: 'hidden', borderColor: 'black', borderWidth: 2, borderStyle: 'solid', backgroundColor: 'green', justifyContent: 'center', alignItems: 'center', }, searchBtnText: { fontSize: 15, color: 'white', }, list: { flex: 1, padding: 30, backgroundColor: 'rgb(39, 174, 96)' }, row: { margin: 8, flexDirection: 'row', justifyContent: 'space-between' }, title: { fontSize: 20, color: 'white' } }); export default ThanksALot;
src/pages/404.js
derrickyoo/derrickyoo.com
import React from 'react' import Layout from '../components/layout' import SEO from '../components/seo' const NotFoundPage = () => ( <Layout> <SEO title="404: Not found" /> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) export default NotFoundPage
src/js/index.js
Tonius/factolculator
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.css'; import App from './App'; // Render the main app component, starting the web application. ReactDOM.render(<App />, document.getElementById('app'));
docs/src/app/components/pages/components/SvgIcon/ExampleIcons.js
skarnecki/material-ui
import React from 'react'; import ActionHome from 'material-ui/svg-icons/action/home'; import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff'; import FileCloudDownload from 'material-ui/svg-icons/file/cloud-download'; import HardwareVideogameAsset from 'material-ui/svg-icons/hardware/videogame-asset'; import {red500, yellow500, blue500} from 'material-ui/styles/colors'; const iconStyles = { marginRight: 24, }; const SvgIconExampleIcons = () => ( <div> <ActionHome style={iconStyles} /> <ActionFlightTakeoff style={iconStyles} color={red500} /> <FileCloudDownload style={iconStyles} color={yellow500} /> <HardwareVideogameAsset style={iconStyles} color={blue500} /> </div> ); export default SvgIconExampleIcons;
react/gameday2/components/embeds/EmbedNotSupported.js
fangeugene/the-blue-alliance
import React from 'react' const EmbedNotSupported = () => { const containerStyles = { margin: 20, textAlign: 'center', } const textStyles = { color: '#ffffff', } return ( <div style={containerStyles}> <p style={textStyles}>This webcast is not supported.</p> </div> ) } export default EmbedNotSupported
src/index.js
karim88/karim88.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.hydrate(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
src/components/Preview/Preview.js
chengjianhua/templated-operating-system
import React, { Component } from 'react'; import ReactServer from 'react-dom/server'; import ReactDOM, { findDOMNode } from 'react-dom'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; // import s from './Preview.css'; const styles = { root: { width: '375px', height: '667px', }, }; // @withStyles(s) export default class MyComponent extends Component { static propTypes = { children: PropTypes.node, }; static defaultProps = { children: null, }; componentDidMount() { // const { contentWindow: { document: iframeDocument } } = this.iframe; // console.log(iframeDocument); } iframeRef = (ref) => { this.iframe = ref; }; renderContent = () => { const { children } = this.props; const html = ReactDOM.renderToString( <html lang="zh-CN"> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>预览手机展示</title> <body> {children} </body> </html>, ); return html; }; render() { const { children, ...props } = this.props; return ( <div ref={this.iframeRef} style={styles.root} {...props} > {children} </div> ); } }
client/src/components/Admin/Categories/CategoryList.js
hutchgrant/react-boilerplate
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../../actions/admin'; class CategoryList extends Component { render() { return ( <div> <h2 className="text-center">Category List</h2> </div> ); } }; function mapStateToProps({ auth }) { return { auth }; } export default connect(mapStateToProps, actions)(CategoryList);
frontend/src/admin/header/LogoutButton.js
rabblerouser/core
import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { logout } from '../actions/'; import { Button } from '../common'; const StyledLogoutButton = styled(Button)` background-color: ${props => props.theme.primaryColour}; color: white; border: 1px solid white; border-radius: 4px; font-size: 20px; `; const LogoutButton = ({ onLogout }) => ( <StyledLogoutButton onClick={onLogout}>Logout</StyledLogoutButton> ); const mapDispatchToProps = dispatch => ({ onLogout: () => dispatch(logout()), }); export default connect(() => ({}), mapDispatchToProps)(LogoutButton);
ui/js/components/Show.js
ericsoderberg/pbc-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { loadItem, unloadItem } from '../actions'; import ItemHeader from './ItemHeader'; import Loading from './Loading'; import NotFound from './NotFound'; class Show extends Component { componentDidMount() { this._load(this.props); } componentWillReceiveProps(nextProps) { if ((nextProps.category !== this.props.category || nextProps.id !== this.props.id || !nextProps.item)) { this._load(nextProps); } if (nextProps.item) { document.title = nextProps.item.name; } } componentWillUnmount() { const { category, dispatch, id } = this.props; dispatch(unloadItem(category, id)); } _load(props) { const { category, dispatch, id, item, } = props; if (item) { document.title = item.name; } else { dispatch(loadItem(category, id)); } } render() { const { actions, category, Contents, item, notFound, title, } = this.props; let contents; if (item) { contents = <Contents item={item} />; } else if (notFound) { contents = <NotFound />; } else { contents = <Loading />; } return ( <main> <ItemHeader title={title} category={category} item={item} actions={actions} /> {contents} </main> ); } } Show.propTypes = { actions: PropTypes.arrayOf(PropTypes.element), category: PropTypes.string.isRequired, Contents: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, id: PropTypes.string.isRequired, item: PropTypes.object, notFound: PropTypes.bool, title: PropTypes.string, }; Show.defaultProps = { actions: [], item: undefined, notFound: false, title: undefined, }; Show.contextTypes = { router: PropTypes.any, }; const select = (state, props) => ({ id: props.match.params.id, item: state[props.match.params.id], notFound: state.notFound[props.match.params.id], }); export default connect(select)(Show);
src/js/components/icons/base/LinkBottom.js
odedre/grommet-final
/** * @description LinkBottom SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M12,5 L12,23 M4,13 L12,5 L20,13 M2,2 L22,2" transform="matrix(1 0 0 -1 0 24)"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-link-bottom`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'link-bottom'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,5 L12,23 M4,13 L12,5 L20,13 M2,2 L22,2" transform="matrix(1 0 0 -1 0 24)"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'LinkBottom'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
docs/src/examples/elements/Divider/Types/DividerExampleHorizontal.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Divider, Input, Segment } from 'semantic-ui-react' const DividerExampleHorizontal = () => ( <Segment basic textAlign='center'> <Input action={{ color: 'blue', content: 'Search' }} icon='search' iconPosition='left' placeholder='Order #' /> <Divider horizontal>Or</Divider> <Button color='teal' content='Create New Order' icon='add' labelPosition='left' /> </Segment> ) export default DividerExampleHorizontal
src/components/BannerNavigation/BannerNavigationWithContent.js
wfp/ui
import PropTypes from 'prop-types'; import React from 'react'; import { BannerNavigation, BannerNavigationItem } from './BannerNavigation'; import Search from '../Search'; import Link from '../Link'; const linkList = [ { name: 'WFPgo', link: 'https://go.wfp.org/' }, { name: 'Communities', link: 'https://communities.wfp.org/' }, { name: 'Manuals', link: 'https://manuals.wfp.org/' }, { name: 'GoDocs', link: 'https://godocs.wfp.org/' }, { name: 'WeLearn', link: 'https://welearn.wfp.org/' }, { name: 'Dashboard', link: 'https://dashboard.wfp.org/' }, { name: 'OPweb', link: 'https://opweb.wfp.org/' }, { name: 'Self-Service', link: 'https://selfservice.go.wfp.org/' }, { name: 'UN Booking Hub', link: 'https://humanitarianbooking.wfp.org/' }, { name: 'WFP.org', link: 'https://wfp.org/' }, ]; const BannerNavigationWithContent = ({ searchOnChange, search, ...other }) => ( <BannerNavigation {...other}> {linkList.map((e) => ( <BannerNavigationItem> <Link href={e.link} target="_blank"> {e.name} </Link> </BannerNavigationItem> ))} </BannerNavigation> ); BannerNavigationWithContent.propTypes = { /** * The CSS class name to be placed on the wrapping element. */ className: PropTypes.string, /** * Specify the max-width on desktop devices (same as \`Wrapper\` component) */ pageWidth: PropTypes.oneOf(['sm', 'md', 'lg', 'full']), /** * Allows to disable the search input */ search: PropTypes.bool, /** * A onChange Function for the search */ searchOnChange: PropTypes.func, }; BannerNavigationWithContent.defaultProps = { search: false, searchOnChange: () => {}, }; export { BannerNavigationWithContent };
modules/Redirect.js
aaron-goshine/react-router
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { formatPattern } from './PatternUtils' import { falsy } from './InternalPropTypes' const { string, object } = React.PropTypes /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ const Redirect = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.from) route.path = route.from route.onEnter = function (nextState, replace) { const { location, params } = nextState let pathname if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params) } else if (!route.to) { pathname = location.pathname } else { let routeIndex = nextState.routes.indexOf(route) let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1) let pattern = parentPattern.replace(/\/*$/, '/') + route.to pathname = formatPattern(pattern, params) } replace({ pathname, query: route.query || location.query, state: route.state || location.state }) } return route }, getRoutePattern(routes, routeIndex) { let parentPattern = '' for (let i = routeIndex; i >= 0; i--) { const route = routes[i] const pattern = route.path || '' parentPattern = pattern.replace(/\/*$/, '/') + parentPattern if (pattern.indexOf('/') === 0) break } return '/' + parentPattern } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<Redirect> elements are for router configuration only and should not be rendered' ) } }) export default Redirect
src/encoded/static/components/item-pages/components/WorkflowDetailPane/ParameterDetailBody.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; export const ParameterDetailBody = React.memo(function ParameterDetailBody({ node, minHeight }){ return ( <div style={typeof minHeight === 'number' ? { minHeight } : null}> <div className="information"> <div className="row"> <div className="col col-sm-4 box"> <span className="text-600">Parameter Name</span> <h3 className="text-300 text-truncate">{ node.name || node.meta.name }</h3> </div> <div className="col-sm-8 box"> <span className="text-600">Value Used</span> <h4 className="text-300 text-truncate"> <code>{ node.meta.run_data.value }</code> </h4> </div> </div> </div> <hr/> </div> ); });
src/containers/Mcml/Mcml.js
hahoocn/hahoo-admin
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar'; import FormControl from 'react-bootstrap/lib/FormControl'; import toFloat from 'validator/lib/toFloat'; import isDecimal from 'validator/lib/isDecimal'; import config from './config'; import { filterPage } from '../../utils/filter'; import ListRow from './ListRow'; import { Navbar, PageWrapper, PageHeader, List, BtnAdd, BtnRefresh, Pagination, Dialog, Toast, ShowError } from '../../components'; import { getList, setListStatus, publish, del, order, getScrollPosition, cleanError, cleanLoading } from '../../actions/mcml'; class Mcml extends React.Component { static propTypes = { data: React.PropTypes.object, dispatch: React.PropTypes.func, params: React.PropTypes.object } static contextTypes = { router: React.PropTypes.object.isRequired } constructor(props) { super(props); this.state.pageSize = config.pageSize; this.pageSelect = this.pageSelect.bind(this); this.handleDelConfirm = this.handleDelConfirm.bind(this); this.changeOrderIdConfirm = this.changeOrderIdConfirm.bind(this); this.refresh = this.refresh.bind(this); } state = { pageSize: 10, isLoading: false, del: { isShowDialog: false, id: undefined, }, order: { isShowDialog: false, id: undefined, orderId: undefined, newOrderId: undefined, } } componentWillMount() { this.setState({ isLoading: true }); const { data, dispatch } = this.props; if (data.error) { dispatch(cleanError()); } if (data.isLoading || data.isUpdating) { dispatch(cleanLoading()); } } componentDidMount() { const page = filterPage(this.props.params.page); if (page === -1) { this.context.router.replace('/notfound'); } else { const { data, dispatch } = this.props; if (page !== data.page || data.items.length === 0 || (data.listUpdateTime && ((Date.now() - data.listUpdateTime) > config.listRefreshTime))) { dispatch(setListStatus('initPage')); dispatch(getList(config.api.resource, page, this.state.pageSize)); } } if (this.state.isLoading) { setTimeout(() => { this.setState({ isLoading: false }); }, 50); } } shouldComponentUpdate(nextProps, nextState) { const { data } = this.props; const page = filterPage(nextProps.params.page); if (page === -1) { return false; } if (page !== data.page || data.items.length === 0 || (data.listUpdateTime && ((Date.now() - data.listUpdateTime) > config.listRefreshTime))) { return true; } if (data.shouldUpdate || nextProps.data.shouldUpdate) { return true; } if (nextState.del !== this.state.del || nextState.order !== this.state.order || nextState.isLoading !== this.state.isLoading) { return true; } return false; } componentDidUpdate(prevProps, prevState) { const { data, dispatch } = this.props; if (!data.isLoading && prevProps.data.isLoading && !data.error) { switch (data.listStatus) { case 'initPage': window.scrollTo(0, this.props.data.scrollY); break; case 'switchingPage': window.scrollTo(0, 0); this.context.router.push(`/${config.module}/list/${data.page}`); break; default: } dispatch(setListStatus('ok')); } else { // 直接从浏览器输入页码 const page = filterPage(this.props.params.page); if (page === -1) { this.context.router.replace('/notfound'); } else if (!data.isLoading && page !== data.page && !data.error && data.listStatus === 'ok') { dispatch(getList(config.api.resource, page, this.state.pageSize)); } if (prevState.isLoading && !this.state.isLoading) { window.scrollTo(0, this.props.data.scrollY); } } } componentWillUnmount() { this.props.dispatch(getScrollPosition(window.scrollY)); } pageSelect(page) { const { dispatch } = this.props; dispatch(setListStatus('switchingPage')); dispatch(getList(config.api.resource, page, this.state.pageSize)); } refresh() { const { dispatch, data } = this.props; dispatch(getList(config.api.resource, data.page, this.state.pageSize)); } handleDelConfirm(code) { if (code === 1) { this.props.dispatch(del(config.api.resource, this.state.del.id)); } this.setState({ del: { isShowDialog: false, id: undefined } }); } changeOrderIdConfirm(code) { if (code === 1) { if (isDecimal(`${this.state.order.newOrderId}`)) { const newOrderId = toFloat(`${this.state.order.newOrderId}`); if (newOrderId && newOrderId > 0 && newOrderId !== toFloat(`${this.state.order.orderId}`)) { const { dispatch, params } = this.props; dispatch(order(config.api.resource, this.state.order.id, 'changeOrderId', params.page, this.state.pageSize, newOrderId)); } } } this.setState({ order: { isShowDialog: false, id: undefined, orderId: undefined, newOrderId: undefined } }); } render() { const { data, dispatch, params } = this.props; const { page } = params; const { pageSize } = this.state; let loading; if (data.isLoading || this.state.isLoading) { loading = <Toast type="loading" title="加载数据" isBlock />; } if (data.isUpdating) { loading = <Toast type="loading" title="正在更新" isBlock />; } let error; if (!loading && data.error) { error = <ShowError error={data.error} key={Math.random()} onClose={() => dispatch(cleanError())} />; } let pageWrapper; let dialog; if (!this.state.isLoading && data.items && data.items.length > 0) { if (this.state.del.isShowDialog) { dialog = <Dialog title="确认" info="您确定删除吗?" type="confirm" onClick={this.handleDelConfirm} />; } if (this.state.order.isShowDialog) { dialog = (<Dialog title="修改排序码" info={<FormControl type="number" value={this.state.order.newOrderId} onChange={e => this.setState({ order: Object.assign({}, this.state.order, { newOrderId: e.target.value }) })} />} type="confirm" onClick={this.changeOrderIdConfirm} />); } const rows = data.items.map(item => (<ListRow module={config.module} key={item.id} item={item} onDelete={id => this.setState({ del: { isShowDialog: true, id } })} onPublish={id => dispatch(publish(config.api.resource, id, true))} onUnPublish={id => dispatch(publish(config.api.resource, id, false))} onMoveUp={id => dispatch(order(config.api.resource, id, 'up', page, pageSize))} onMoveDown={id => dispatch(order(config.api.resource, id, 'down', page, pageSize))} onMoveTo={(id, orderId) => dispatch(order(config.api.resource, id, 'changeOrderId', page, pageSize, orderId))} onPopOrderIdPannel={(id, orderId) => this.setState({ order: { isShowDialog: true, id, orderId, newOrderId: orderId } })} />)); const pagination = (<Pagination page={data.page} pageSize={pageSize} recordCount={data.totalCount} pageSelect={this.pageSelect} />); pageWrapper = (<div> <PageHeader title={config.moduleName} subTitle="列表"> <ButtonToolbar> <BtnAdd onItemClick={() => this.context.router.push(`/${config.module}/add`)} /> <BtnRefresh onItemClick={this.refresh} /> </ButtonToolbar> </PageHeader> <List> {rows && rows} </List> {pagination && pagination} </div>); } return ( <div> <Helmet title={config.pageTitle} /> <Navbar activeKey={config.module} /> {dialog && dialog} {error && error} {loading && loading} <PageWrapper> {pageWrapper} </PageWrapper> </div> ); } } const mapStateToProps = (state) => { const select = { data: state.mcml }; return select; }; export default connect(mapStateToProps)(Mcml);
frontend/src/Settings/Indexers/Indexers/AddIndexerModal.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import AddIndexerModalContentConnector from './AddIndexerModalContentConnector'; function AddIndexerModal({ isOpen, onModalClose, ...otherProps }) { return ( <Modal isOpen={isOpen} onModalClose={onModalClose} > <AddIndexerModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } AddIndexerModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default AddIndexerModal;
src/js/components/Map.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import CSSClassnames from '../utils/CSSClassnames'; import Intl from '../utils/Intl'; const CLASS_ROOT = CSSClassnames.MAP; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class ResourceMap extends Component { constructor(props, context) { super(props, context); this._onResize = this._onResize.bind(this); this._layout = this._layout.bind(this); this._onEnter = this._onEnter.bind(this); this._onLeave = this._onLeave.bind(this); this.state = { ...(this._stateFromProps(props)), height: 100, width: 100, paths: [] }; } componentDidMount () { window.addEventListener('resize', this._onResize); this._layout(); } componentWillReceiveProps (nextProps) { this.setState(this._stateFromProps(nextProps), this._layout); } componentWillUnmount () { window.removeEventListener('resize', this._onResize); } _hashItems (data) { let result = {}; data.categories.forEach(category => { category.items.forEach(item => { result[item.id] = item; }); }); return result; } _children (parentId, links, items) { let result = []; links.forEach(link => { if (link.parentId === parentId) { result.push(items[link.childId]); } }); return result; } _parents (childId, links, items) { let result = []; links.forEach((link) => { if (link.childId === childId) { result.push(items[link.parentId]); } }); return result; } _buildAriaLabels (data, items) { const { intl } = this.context; let labels = {}; data.categories.forEach(category => { category.items.forEach(item => { const children = this._children(item.id, data.links, items); const parents = this._parents(item.id, data.links, items); let message = ''; if (children.length === 0 && parents.length === 0) { message = Intl.getMessage(intl, 'No Relationship'); } else { if (parents.length > 0) { const prefix = Intl.getMessage(intl, 'Parents'); const labels = parents.map(item => item.label || item.node).join(); message += `${prefix}: (${labels})`; } if (children.length > 0) { if (parents.length > 0) { message += ', '; } const prefix = Intl.getMessage(intl, 'Children'); const labels = children.map(item => item.label || item.node).join(); message += `${prefix}: (${labels})`; } } labels[item.id] = message; }); }); return labels; } _stateFromProps (props, state = {}) { const activeId = props.hasOwnProperty('active') ? props.active : state.activeId; const items = this._hashItems(props.data); return { activeId: activeId, ariaLabels: this._buildAriaLabels(props.data, items), items: items }; } _coords (id, containerRect) { const element = document.getElementById(id); const rect = element.getBoundingClientRect(); const left = rect.left - containerRect.left; const top = rect.top - containerRect.top; const midX = left + (rect.width / 2); const midY = top + (rect.height / 2); return { top: [midX, top], bottom: [midX, top + rect.height], left: [left, midY], right: [left + rect.width, midY] }; } _buildPaths (map) { const { linkColorIndex, data: { links }, vertical } = this.props; const { activeId } = this.state; const rect = map.getBoundingClientRect(); const paths = links.map((link, index) => { const parentCoords = this._coords(link.parentId, rect); const childCoords = this._coords(link.childId, rect); let p1, p2; if (vertical) { if (parentCoords.right[0] < childCoords.left[0]) { p1 = parentCoords.right; p2 = childCoords.left; } else { p1 = parentCoords.left; p2 = childCoords.right; } } else { if (parentCoords.bottom[1] < childCoords.top[1]) { p1 = parentCoords.bottom; p2 = childCoords.top; } else { p1 = parentCoords.top; p2 = childCoords.bottom; } } let commands = `M${p1[0]},${p1[1]}`; const midX = p1[0] + ((p2[0] - p1[0]) / 2); const midY = p1[1] + ((p2[1] - p1[1]) / 2); if (vertical) { commands += ` Q ${midX + ((p1[0] - midX) / 2)},${p1[1]}` + ` ${midX},${midY}`; commands += ` Q ${midX - ((p1[0] - midX) / 2)},${p2[1]}` + ` ${p2[0]},${p2[1]}`; } else { commands += ` Q ${p1[0]},${midY + ((p1[1] - midY) / 2)}` + ` ${midX},${midY}`; commands += ` Q ${p2[0]},${midY - ((p1[1] - midY) / 2)}` + ` ${p2[0]},${p2[1]}`; } const pathColorIndex = link.colorIndex || linkColorIndex; const classes = classnames( `${CLASS_ROOT}__path`, { [`${CLASS_ROOT}__path--active`]: (activeId === link.parentId || activeId === link.childId), [`${COLOR_INDEX}-${pathColorIndex}`]: pathColorIndex } ); return ( <path key={index} fill="none" className={classes} d={commands} /> ); }); return paths; } _layout () { const map = findDOMNode(this._mapRef); if (map) { this.setState({ width: map.scrollWidth, height: map.scrollHeight, paths: this._buildPaths(map) }); } } _onResize () { // debounce clearTimeout(this._layoutTimer); this._layoutTimer = setTimeout(this._layout, 50); } _onEnter (id) { this.setState({activeId: id}, this._layout); if (this.props.onActive) { this.props.onActive(id); } } _onLeave () { this.setState({activeId: undefined}, this._layout); if (this.props.onActive) { this.props.onActive(undefined); } } _renderItems (items) { const { data } = this.props; const { activeId, ariaLabels } = this.state; return items.map((item, index) => { const active = activeId === item.id || data.links.some(link => { return ((link.parentId === item.id || link.childId === item.id) && (link.parentId === activeId || link.childId === activeId)); }); const classes = classnames( `${CLASS_ROOT}__item`, { [`${CLASS_ROOT}__item--active`]: active, [`${CLASS_ROOT}__item--plain`]: (item.node && typeof item.node !== 'string') } ); return ( <li key={index} id={item.id} className={classes} aria-label={`${item.label || item.node}, ${ariaLabels[item.id]}`} onMouseEnter={this._onEnter.bind(this, item.id)} onMouseLeave={this._onLeave.bind(this, item.id)}> {item.node || item.label} </li> ); }); } _renderCategories (categories) { return categories.map(category => { return ( <li key={category.id} className={`${CLASS_ROOT}__category`}> <div className={`${CLASS_ROOT}__category-label`}> {category.label} </div> <ul className={`${CLASS_ROOT}__category-items`}> {this._renderItems(category.items)} </ul> </li> ); }); } render () { const { className, data, vertical, ...props } = this.props; delete props.active; delete props.colorIndex; delete props.linkColorIndex; delete props.onActive; const { height, paths, width } = this.state; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--vertical`]: vertical }, className ); let categories; if (data.categories) { categories = this._renderCategories(data.categories); } return ( <div ref={ref => this._mapRef = ref} {...props} className={classes}> <svg className={`${CLASS_ROOT}__links`} width={width} height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="xMidYMid meet"> {paths} </svg> <ol className={`${CLASS_ROOT}__categories`}> {categories} </ol> </div> ); } } ResourceMap.contextTypes = { intl: PropTypes.object }; ResourceMap.propTypes = { active: PropTypes.string, data: PropTypes.shape({ categories: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.node, items: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.string, node: PropTypes.node })) })), links: PropTypes.arrayOf(PropTypes.shape({ childId: PropTypes.string.isRequired, colorIndex: PropTypes.string, parentId: PropTypes.string.isRequired })) }).isRequired, linkColorIndex: PropTypes.string, onActive: PropTypes.func, vertical: PropTypes.bool }; ResourceMap.defaultProps = { linkColorIndex: 'graph-1' };
src/services/TplEmbeddedLoader.js
webcerebrium/ec-react15-lib
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Logger } from './Logger'; import { getDocumentContext } from './TplContext'; import { matchConditions } from './DocumentCondition'; import { findDocumentElements } from './DocumentSelector'; import { downloadTemplateData } from './TplRouteData'; import ApplicationContainer from './../containers/ApplicationContainer'; const getTemplateDocument = tpl => (tpl ? `--Template-${tpl}` : ''); export const onStartApplications = (store, mount, callback) => { const context = getDocumentContext(store.getState()); mount.forEach((potentialMount) => { // 1) - there has to be potentialMount.selector on the page currently const elementRoot = findDocumentElements(potentialMount.selector, document); // eslint-disable-line Logger.of('TplEmbeddedLoader.onStartApplication').info('check for mounting', potentialMount, 'elementRoot=', elementRoot); if (elementRoot) { // 2) - potentialMount.condition should be valid. let match = true; if (potentialMount.condition) { match = matchConditions({}, potentialMount.condition, context); Logger.of('TplEmbeddedLoader.onStartApplication').info('check for conditions', potentialMount.condition, match); } if (match) { // confirmed 'route' match const route = potentialMount; const { dispatch } = store; // we have both element and condition match, mounting it // and how to pass ... anything... ? it has global redux mapping... Logger.of('TplEmbeddedLoader.onStartApplication').info('mounting template', potentialMount.template); const tpl = getTemplateDocument(potentialMount.template); dispatch({ type: 'SET_DATA', payload: ['template', tpl] }); downloadTemplateData({ route, tpl, store, callback: () => { // notifying all reducers of what we currently have in the store. // this is used for setting up defaults at them. dispatch({ type: 'INIT_DATA', payload: store.getState() }); // Logger.of('TplRouteLoader.Ready').info('state=', store.getState()); // onDataReady(route, getDocumentContext(store.getState(), dispatch), callback); // route is released, we are starting to run hooks from plugins const ecOptions = store.getState().globals.ecOptions; if (ecOptions.plugins && ecOptions.plugins.length) { ecOptions.plugins.forEach((plugin) => { if (typeof plugin.onDataReady === 'function') { plugin.onDataReady({ route, tpl, store }); } }); } if (typeof callback === 'function') callback(); } }); const application = ( <Provider store={store}> <ApplicationContainer /> </Provider> ); render(application, elementRoot); } } }); }; export default { onStartApplications };
react/features/mobile/navigation/components/conference/ConferenceNavigationContainerRef.js
jitsi/jitsi-meet
import React from 'react'; export const conferenceNavigationRef = React.createRef(); /** * User defined navigation action included inside the reference to the container. * * @param {string} name - Destination name of the route that has been defined somewhere. * @param {Object} params - Params to pass to the destination route. * @returns {Function} */ export function navigate(name: string, params?: Object) { return conferenceNavigationRef.current?.navigate(name, params); } /** * User defined navigation action included inside the reference to the container. * * @returns {Function} */ export function goBack() { return conferenceNavigationRef.current?.goBack(); } /** * User defined navigation action included inside the reference to the container. * * @param {Object} params - Params to pass to the destination route. * @returns {Function} */ export function setParams(params: Object) { return conferenceNavigationRef.current?.setParams(params); }
Redux/src/index.js
il-tmfv/ReactTutorialMaxP
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' require('./styles/app.css') import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <div className='app'> <App /> </div> </Provider>, document.getElementById('root') )
client/providers/ServerProvider.js
Sing-Li/Rocket.Chat
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { Info as info } from '../../app/utils'; import { ServerContext } from '../contexts/ServerContext'; import { APIClient } from '../../app/utils/client'; const absoluteUrl = (path) => Meteor.absoluteUrl(path); const callMethod = (methodName, ...args) => new Promise((resolve, reject) => { Meteor.call(methodName, ...args, (error, result) => { if (error) { reject(error); return; } resolve(result); }); }); const callEndpoint = (httpMethod, endpoint, ...args) => { const allowedHttpMethods = ['get', 'post', 'delete']; if (!httpMethod || !allowedHttpMethods.includes(httpMethod.toLowerCase())) { throw new Error('Invalid http method provided to "useEndpoint"'); } if (!endpoint) { throw new Error('Invalid endpoint provided to "useEndpoint"'); } if (endpoint[0] === '/') { return APIClient[httpMethod.toLowerCase()](endpoint.slice(1), ...args); } return APIClient.v1[httpMethod.toLowerCase()](endpoint, ...args); }; const uploadToEndpoint = (endpoint, params, formData) => { if (endpoint[0] === '/') { return APIClient.upload(endpoint.slice(1), params, formData).promise; } return APIClient.v1.upload(endpoint, params, formData).promise; }; const getStream = (streamName, options = {}) => new Meteor.Streamer(streamName, options); const contextValue = { info, absoluteUrl, callMethod, callEndpoint, uploadToEndpoint, getStream, }; export function ServerProvider({ children }) { return <ServerContext.Provider children={children} value={contextValue} />; }
app/javascript/mastodon/features/ui/components/column_header.js
mhffdq/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <i className={`fa fa-fw fa-${icon} column-header__icon`} />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/Post.js
drop-table-ryhmatyo/tekislauta-front
import React, { Component } from 'react'; import { Link } from 'react-router'; import Utilities from './Utilities'; import './styles/Post.css'; class Post extends Component { constructor(props) { super(props); this.containerClassName = 'Post Post--reply'; } getIdColor() { const ip = this.props.data.ip; let r = parseInt(ip.substr(0, 2), 16); let g = parseInt(ip.substr(2, 2), 16); let b = parseInt(ip.substr(4, 2), 16); const modifier = parseInt(ip.substr(6, 2), 16); // the ip has 4 bytes, we only need 3. We could use the last one for alpha but that's trash // instead, we'll just xor r ^= modifier; g ^= modifier; b ^= modifier; let hsl = Utilities.RgbToHsl(r, g, b); hsl['s'] -= 20; // desaturate a little for that web 3.0 look return `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`; } render() { const idStyle = { backgroundColor: this.getIdColor() } return ( <div className={this.containerClassName} id={'p' + this.props.data.id}> <div className='Post__header'> <span className='Post__header__title'> <Link className='Post__header__title__anchor' to={'/boards/' + this.props.board + '/thread/' + this.props.data.id}> {this.props.data.subject} </Link> </span> <span id={this.props.data.id} className='Post__header__posterName'> Anonymous </span> <span className='Post__header__id'>(ID: <span className='Post__header__id__value' style={idStyle}>{this.props.data.ip}</span>) </span> <time className='Post__header__timestamp'>{new Date(this.props.data.post_time * 1000).toLocaleString("fi-FI") }</time> <span className='Post__header__postNumber'> No.{this.props.data.id}</span> <ReplyLink onClickFunc={this.props.onReplyClicked} board={this.props.board} postId={this.props.data.id} /> </div> <div className='Post__content'> <ThreadReply message={this.props.data.message} /> </div> </div> ); } } class ReplyLink extends Component { render() { const link = `/boards/${this.props.board}/thread/${this.props.postId}`; if (this.props.onClickFunc !== undefined) { return ( <span className='ReplyLink'> [<a href='#' onClick={() => this.props.onClickFunc(this.props.postId) }>Reply</a>] </span> ); } else { return ( <span className='ReplyLink'> [<Link to={link}>Reply</Link>] </span> ); } } } class ThreadReply extends Component { render() { var replyId = this.props.message.match(/>> \b\d{1,8}/); if (replyId) { replyId = replyId[0]; return ( <p> <a href={'#' + replyId.substr(3) }>{replyId}</a> {this.props.message.replace(/>> \b\d{1,8}/, '') } </p> ) } return ( <p>{this.props.message}</p> ); } } class OriginalPost extends Post { // thread starter constructor(props) { super(props); this.containerClassName = 'Post Post--op'; } } class ThreadlistOriginalPost extends OriginalPost { constructor(props) { super(props); this.containerClassName = 'Post Post--op Post--op_threadlist'; } } export { Post as default, OriginalPost, ThreadlistOriginalPost };
docs/app/Examples/modules/Dropdown/Types/DropdownExamplePointingTwo.js
koenvg/Semantic-UI-React
import React from 'react' import { Dropdown, Menu } from 'semantic-ui-react' const DropdownExamplePointingTwo = () => ( <Menu vertical> <Menu.Item> Home </Menu.Item> <Dropdown text='Messages' pointing='left' className='link item'> <Dropdown.Menu> <Dropdown.Item>Inbox</Dropdown.Item> <Dropdown.Item>Starred</Dropdown.Item> <Dropdown.Item>Sent Mail</Dropdown.Item> <Dropdown.Item>Drafts (143)</Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item>Spam (1009)</Dropdown.Item> <Dropdown.Item>Trash</Dropdown.Item> </Dropdown.Menu> </Dropdown> <Menu.Item> Browse </Menu.Item> <Menu.Item> Help </Menu.Item> </Menu> ) export default DropdownExamplePointingTwo
packages/screenie-cli/src/browser-reporter/components/tests-chart.js
ParmenionUX/screenie
import React from 'react' import { connect } from 'react-redux' export default connect( state => ({ status: state.status, }), )(({ status }) => <div style={styles.container}> <svg style={styles.svg}> {renderTests(status.tests)} </svg> </div> ) const PADDING = 20 const TEST_PADDING = 30 const SNAPSHOT_PADDING = 5 const SNAPSHOT_SIZE = 16 function renderTests(tests) { let x = PADDING return tests.map(test => { const startX = x if (test.snapshots != null) { const snapshots = test.snapshots.map(snapshot => { const thisX = x x += SNAPSHOT_SIZE + SNAPSHOT_PADDING return renderSnapshotOrTest(snapshot, test, thisX) }) return [ <rect x={startX} width={x - startX} y={0} height={SNAPSHOT_SIZE + PADDING + PADDING} fill="whitesmoke" />, ...snapshots, <line x1={x + SNAPSHOT_SIZE + (TEST_PADDING / 2)} x2={x + SNAPSHOT_SIZE + (TEST_PADDING / 2)} y1={PADDING} y2={PADDING + SNAPSHOT_SIZE} stroke="gray" strokeWidth={1} />, ] } const thisX = x x += SNAPSHOT_SIZE + TEST_PADDING return [ renderSnapshotOrTest(test, null, thisX), <line x1={thisX + SNAPSHOT_SIZE + (TEST_PADDING / 2)} x2={thisX + SNAPSHOT_SIZE + (TEST_PADDING / 2)} y1={PADDING} y2={PADDING + SNAPSHOT_SIZE} stroke="gray" strokeWidth={1} />, ] }) } function renderSnapshotOrTest(testOrSnapshot, parentTest, x) { let snapshotStatusStyle = null if (testOrSnapshot.passed) { snapshotStatusStyle = styles.snapshotPassed } else if (testOrSnapshot.passed === false) { snapshotStatusStyle = styles.snapshotFailed } return ( <rect style={{ ...styles.snapshot, ...snapshotStatusStyle, }} x={x} y={PADDING} > <title> {parentTest != null ? `${parentTest.name} - ${testOrSnapshot.name}` : testOrSnapshot.name } </title> </rect> ) } const styles = { container: { width: '100%', }, svg: { width: '100%', height: 300, }, snapshot: { fill: 'gray', width: SNAPSHOT_SIZE, height: SNAPSHOT_SIZE, }, snapshotPassed: { fill: 'green', }, snapshotFailed: { fill: 'red', }, }
actor-apps/app-web/src/app/components/ToolbarSection.react.js
sc4599/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import { IntlMixin } from 'react-intl'; import classnames from 'classnames'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import DialogStore from 'stores/DialogStore'; import ActivityStore from 'stores/ActivityStore'; //import AvatarItem from 'components/common/AvatarItem.react'; const getStateFromStores = () => { return { dialogInfo: DialogStore.getSelectedDialogInfo(), isActivityOpen: ActivityStore.isOpen() }; }; @ReactMixin.decorate(IntlMixin) class ToolbarSection extends React.Component { state = { dialogInfo: null, isActivityOpen: false }; constructor(props) { super(props); DialogStore.addSelectedChangeListener(this.onChange); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { DialogStore.removeSelectedChangeListener(this.onChange); ActivityStore.removeChangeListener(this.onChange); } onClick = () => { if (!this.state.isActivityOpen) { ActivityActionCreators.show(); } else { ActivityActionCreators.hide(); } }; onChange = () => { this.setState(getStateFromStores()); }; render() { const info = this.state.dialogInfo; const isActivityOpen = this.state.isActivityOpen; let infoButtonClassName = classnames('button button--icon', { 'button--active': isActivityOpen }); if (info != null) { return ( <header className="toolbar"> <div className="pull-left"> <div className="toolbar__peer row"> <div className="toolbar__peer__body col-xs"> <span className="toolbar__peer__title">{info.name}</span> <span className="toolbar__peer__presence">{info.presence}</span> </div> </div> </div> <div className="toolbar__controls pull-right"> <div className="toolbar__controls__search pull-left hide"> <i className="material-icons">search</i> <input className="input input--search" placeholder={this.getIntlMessage('search')} type="search"/> </div> <div className="toolbar__controls__buttons pull-right"> <button className={infoButtonClassName} onClick={this.onClick}> <i className="material-icons">info</i> </button> <button className="button button--icon hide"> <i className="material-icons">more_vert</i> </button> </div> </div> </header> ); } else { return ( <header className="toolbar"> </header> ); } } } export default ToolbarSection;
src/destinations/render.js
RoyalIcing/gateau
import R from 'ramda' import React from 'react' import { Seed } from 'react-seeds' const resolveContentIn = R.curry(function resolveItemIn(source, path) { //path = R.filter(R.isNil) console.log('resolveContentIn', path, source) path = R.insertAll(1, ['content'], path) return R.path(path, source) }) const variationForItemIn = R.curry(function adjustItemIn(source, path) { const id = R.head(path) return R.path([id, 'variationReference'], source) }) const resolveContentUsing = (ingredients) => { const resolveIngredientReference = resolveContentIn(ingredients) const variationForPath = variationForItemIn(ingredients) return (value, { single = true, set, alter } = {}) => { if (R.isNil(value)) { return } else if (value.mentions != null && value.mentions.length > 0 && value.mentions[0] != null) { console.log('MENTIONS', { set, alter }) if (set) { R.forEach( (item) => item.set(set), result ) } else if (alter) { const path = value.mentions[0] const variation = variationForPath(path) console.log('altering variation', variation) const innerPath = R.tail(path) variation.adjustPath(innerPath, alter) } else { console.log('RESOLVE', value.mentions) const resolved = R.map(resolveIngredientReference, value.mentions) console.log('RESOLVED', resolved) if (resolved == null) { return } return single ? resolved[0] : resolved } } else if (value.texts != null) { return value.texts } else { return value } } } function elementFromText(text) { return { text, references: [], tags: {}, children: [] } } export const renderElement = ({ ingredients, elementRendererForTags }) => { const resolveContent = resolveContentUsing(ingredients) const extra = { elementFromText } const Element = R.converge( R.call, [ R.pipe( R.props(['defaultTags', 'tags']), R.apply(R.mergeWith(R.merge)), elementRendererForTags ), R.prop('mentions'), R.prop('texts'), R.prop('children'), (ignore) => Element, // Have to put in closure as it is currently being assigned R.always(resolveContent), R.always(extra) ] ) Element.renderArray = (options, array) => ( array.map((element, index) => ( <Element key={ index } { ...options } { ...element } /> )) ) return Element } export const DefaultSection = ({ children }) => ( <Seed Component='section' //column margin={{ base: '2rem', top: 0 }} children={ children } /> ) export const DefaultMaster = ({ children }) => ( <Seed padding={{ top: '1rem' }} children={ children } /> ) export const renderTreeUsing = ({ elementRendererForTags, Section = DefaultSection, Master = DefaultMaster }) => ({ ingredients, contentTree }) => { // FIXME: use valueForIngredient instead that encapsulates ingredientVariationIndexes const Element = renderElement({ ingredients, elementRendererForTags }) return ( <Master ingredients={ ingredients }> { contentTree.map((section, sectionIndex) => ( <Section key={ sectionIndex }> { section.map((element, elementIndex) => ( <Element key={ elementIndex } { ...element } /> )) } </Section> )) } </Master> ) }
src/svg-icons/av/repeat.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRepeat = (props) => ( <SvgIcon {...props}> <path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/> </SvgIcon> ); AvRepeat = pure(AvRepeat); AvRepeat.displayName = 'AvRepeat'; AvRepeat.muiName = 'SvgIcon'; export default AvRepeat;
index.js
techiesanchez/rythus-app
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import createLogger from 'redux-logger'; import thunkMiddleware from 'redux-thunk'; import reducers from './reducers'; import { RythusCardsApp } from './components/App'; const middleware = [ thunkMiddleware ]; if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()); } var initialState = { displayedCard: {}, selectedItem: "Encounter", menuItems: [ { name: 'resourcez', active: false }, { name: 'settlementz', active: false }, { name: 'battallionz', active: false }, { name: 'heroz', active: false }, { name: 'merchantz', active: false }, { name: 'dungeonz', active: false }, { name: 'villainz', active: false }, { name: 'monsterz', active: false }, { name: 'encounterz', active: false }, { name: 'rewardz', active: false } ], isFetching: false, cards: {}, discards: {} } var store = createStore(reducers, initialState, applyMiddleware(...middleware)); render( <Provider store={store}> <RythusCardsApp /> </Provider>, document.getElementById('appy') );
src/client/routes.js
obimod/este
import App from './app/app.react'; import Home from './home/index.react'; import Login from './auth/index.react'; import Me from './me/index.react'; import NotFound from './components/notfound.react'; import React from 'react'; import Todos from './todos/index.react'; import {DefaultRoute, NotFoundRoute, Route} from 'react-router'; export default ( <Route handler={App} path="/"> <DefaultRoute handler={Home} name="home" /> <NotFoundRoute handler={NotFound} name="not-found" /> <Route handler={Login} name="login" /> <Route handler={Me} name="me" /> <Route handler={Todos} name="todos" /> </Route> );
stories/index.js
ionutmilica/react-chartjs-components
import React from 'react'; import './ComponentsExample';
src/svg-icons/communication/message.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationMessage = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/> </SvgIcon> ); CommunicationMessage = pure(CommunicationMessage); CommunicationMessage.displayName = 'CommunicationMessage'; export default CommunicationMessage;
ScrollableTabView自定义TarBar/index.android.js
yuanliangYL/ReactNative-Components-Demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class ScrollableTabView extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ScrollableTabView', () => ScrollableTabView);
src/encoded/static/components/viz/FourfrontLogo.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import * as d3 from 'd3'; /** Renders out the 4DN Logo SVG as a React element(s) */ export class FourfrontLogo extends React.PureComponent { static defaultProps = { 'id' : "fourfront_logo_svg", 'circlePathDefinitionOrig' : "m1,30c0,-16.0221 12.9779,-29 29,-29c16.0221,0 29,12.9779 29,29c0,16.0221 -12.9779,29 -29,29c-16.0221,0 -29,-12.9779 -29,-29z", 'circlePathDefinitionHover' : "m3.33331,34.33326c-2.66663,-17.02208 2.97807,-23.00009 29.99997,-31.33328c27.02188,-8.33321 29.66667,22.31102 16.6669,34.66654c-12.99978,12.35552 -15.64454,20.00017 -28.66669,19.00018c-13.02214,-0.99998 -15.33356,-5.31137 -18.00018,-22.33344z", 'textTransformOrig' : "translate(9, 37)", 'textTransformHover' : "translate(48, 24) scale(0.2, 0.6)", 'fgCircleTransformOrig' : "translate(50, 20) scale(0.35, 0.35) rotate(-135)", 'fgCircleTransformHover' : "translate(36, 28) scale(0.7, 0.65) rotate(-135)", 'hoverDelayUntilTransform' : 400, 'title' : "Data Portal" }; static svgElemStyle = { 'verticalAlign' : 'middle', 'display' : 'inline-block', 'height' : '100%', 'paddingBottom' : 10, 'paddingTop' : 10, 'transition' : "padding .3s, transform .3s", 'maxHeight' : 80 }; static svgBGCircleStyle = { 'fill' : "url(#fourfront_linear_gradient)", "stroke" : "transparent", "strokeWidth" : 1 }; static svgTextStyleOut = { 'transition' : "letter-spacing 1s, opacity .7s, stroke .7s, stroke-width .7s, fill .7s", 'fontSize' : 23, 'fill' : '#fff', 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'stroke' : 'transparent', 'strokeWidth' : 0, 'strokeLinejoin' : 'round', 'opacity' : 1, 'letterSpacing' : 0 }; static svgTextStyleIn = { 'transition' : "letter-spacing 1s .4s linear, opacity .7s .4s, stroke .7s 4s, stroke-width .7s 4s, fill .7s .4s", 'letterSpacing' : -14, 'stroke' : 'rgba(0,0,0,0.2)', 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15 }; static svgInnerCircleStyleOut = { 'transition': "opacity 1.2s", 'opacity' : 0, 'fill' : 'transparent', 'strokeWidth' : 15, 'stroke' : 'rgba(0,0,0,0.2)', 'fontSize' : 23, 'fontFamily' : '"Mada","Work Sans",Helvetica,Arial,sans-serif', 'fontWeight' : '600', 'strokeLinejoin' : 'round' }; static svgInnerCircleStyleIn = { 'transition': "opacity 1.2s .6s", 'opacity' : 1 }; constructor(props){ super(props); this.setHoverStateOnDoTiming = _.throttle(this.setHoverStateOnDoTiming.bind(this), 1000); this.setHoverStateOn = this.setHoverStateOn.bind(this); this.setHoverStateOff = this.setHoverStateOff.bind(this); this.svgRef = React.createRef(); this.bgCircleRef = React.createRef(); this.fgTextRef = React.createRef(); this.fgCircleRef = React.createRef(); this.state = { hover : false }; } setHoverStateOn(e){ this.setState({ 'hover': true }, this.setHoverStateOnDoTiming); } setHoverStateOnDoTiming(e){ const { circlePathDefinitionHover, textTransformHover, fgCircleTransformHover, hoverDelayUntilTransform } = this.props; // CSS styles controlled via stylesheets setTimeout(()=>{ const { hover } = this.state; if (!hover) return; // No longer hovering. Cancel. d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionHover); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(700) .attr('transform', textTransformHover); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1200) .attr('transform', fgCircleTransformHover); }, hoverDelayUntilTransform); } setHoverStateOff(e){ const { circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig } = this.props; this.setState({ 'hover' : false }, ()=>{ d3.select(this.bgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('d', circlePathDefinitionOrig); d3.select(this.fgTextRef.current) .interrupt() .transition() .duration(1200) .attr('transform', textTransformOrig); d3.select(this.fgCircleRef.current) .interrupt() .transition() .duration(1000) .attr('transform', fgCircleTransformOrig); }); } renderDefs(){ return ( <defs> <linearGradient id="fourfront_linear_gradient" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238bae"/> <stop offset="1" stopColor="#8ac640"/> </linearGradient> <linearGradient id="fourfront_linear_gradient_darker" x1="1" y1="30" x2="59" y2="30" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#238b8e"/> <stop offset="1" stopColor="#8aa640"/> </linearGradient> </defs> ); } render(){ const { id, circlePathDefinitionOrig, textTransformOrig, fgCircleTransformOrig, onClick, title } = this.props; const { hover } = this.state; return ( <div className={"img-container" + (hover ? " is-hovering" : "")} onClick={onClick} onMouseEnter={this.setHoverStateOn} onMouseLeave={this.setHoverStateOff}> <svg id={id} ref={this.svgRef} viewBox="0 0 60 60" style={FourfrontLogo.svgElemStyle}> { this.renderDefs() } <path d={circlePathDefinitionOrig} style={FourfrontLogo.svgBGCircleStyle} ref={this.bgCircleRef} /> <text transform={textTransformOrig} style={hover ? { ...FourfrontLogo.svgTextStyleOut, ...FourfrontLogo.svgTextStyleIn } : FourfrontLogo.svgTextStyleOut} ref={this.fgTextRef}> 4DN </text> <text transform={fgCircleTransformOrig} style={hover ? { ...FourfrontLogo.svgInnerCircleStyleOut, ...FourfrontLogo.svgInnerCircleStyleIn } : FourfrontLogo.svgInnerCircleStyleOut} ref={this.fgCircleRef}> O </text> </svg> <span className="navbar-title">Data Portal</span> </div> ); } }
server/frontend/components/Header/Header.js
SchadkoAO/FDTD_Solver
import React from 'react'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; export const Header = ({ children }) => ( <AppBar position="static"> <Toolbar> <IconButton color="contrast" aria-label="Menu"> <MenuIcon /> </IconButton> <Typography type="title" color="inherit"> FDTD Solver </Typography> </Toolbar> </AppBar> ); export default Header;
src/js/components/Gallery/GalleryImage.js
jamieallen59/jamieallen
import React from 'react' import PropTypes from 'prop-types' import CSSModules from 'react-css-modules' import styles from './Gallery.less' import { className } from './Gallery' const GalleryImage = ({ imageUrl, onClick, display = true }) => ( <div onClick={onClick} > <img styleName={display ? `${className}__image` : `${className}__image ${className}__image--hidden`} // eslint-disable-line max-len src={imageUrl} role='presentation' /> </div> ) GalleryImage.propTypes = { display: PropTypes.bool, imageUrl: PropTypes.string, onClick: PropTypes.func } export default CSSModules(GalleryImage, styles, { allowMultiple: true })
docs/src/examples/elements/Input/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Types from './Types' import States from './States' import Variations from './Variations' import Usage from './Usage' const InputExamples = () => ( <div> <Types /> <States /> <Variations /> <Usage /> </div> ) export default InputExamples
src/Parser/Hunter/BeastMastery/Modules/Talents/DireFrenzy.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import STATISTIC_ORDER from 'Main/STATISTIC_ORDER'; import { formatPercentage } from 'common/format'; import StatisticBox from 'Main/StatisticBox'; import ItemDamageDone from 'Main/ItemDamageDone'; import Wrapper from 'common/Wrapper'; /* * Dire Frenzy * Causes your pet to enter a frenzy, performing a flurry of 5 attacks on the target, * and gaining 30% increased attack speed for 8 sec, stacking up to 3 times. */ //max stacks pet can have of Dire Frenzy buff const MAX_DIRE_FRENZY_STACKS = 3; const DIRE_FRENZY_DURATION = 8000; class DireFrenzy extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; buffStart = 0; buffEnd = 0; currentStacks = 0; startOfMaxStacks = 0; timeAtMaxStacks = 0; timeBuffed = 0; lastDireFrenzyCast = null; timeCalculated = null; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.lastDireFrenzyCast = event.timestamp; } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_DAMAGE.id) { return; } this.damage += event.amount + (event.absorbed || 0); } on_toPlayerPet_removebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.timeBuffed += event.timestamp - this.buffStart; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.timeAtMaxStacks += event.timestamp - this.startOfMaxStacks; } this.currentStacks = 0; this.timeCalculated = true; } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } if (this.currentStacks > 0) { this.timeBuffed += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.buffStart; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.timeAtMaxStacks += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.startOfMaxStacks; } } this.buffStart = event.timestamp; this.currentStacks = 1; this.timeCalculated = false; } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.DIRE_FRENZY_TALENT.id) { return; } this.currentStacks = event.stack; if (this.currentStacks === MAX_DIRE_FRENZY_STACKS) { this.startOfMaxStacks = event.timestamp; } } on_finished() { if (!this.timeCalculated) { if ((this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) > this.owner.fight.end_time) { if (this.currentStacks > 0) { this.timeBuffed += this.owner.fight.end_time - this.buffStart; } if (this.currentStacks === 3) { this.timeAtMaxStacks += this.owner.fight.end_time - this.startOfMaxStacks; } } else { if (this.currentStacks > 0) { this.timeBuffed += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.buffStart; } if (this.currentStacks === 3) { this.timeAtMaxStacks += (this.lastDireFrenzyCast + DIRE_FRENZY_DURATION) - this.startOfMaxStacks; } } } } get percentUptimeMaxStacks() { return this.timeAtMaxStacks / this.owner.fightDuration; } get percentUptimePet() { return this.timeBuffed / this.owner.fightDuration; } get percentPlayerUptime() { //This calculates the uptime over the course of the encounter of Dire Frenzy for the player return (this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_1.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_2.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_3.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_4.id) + this.combatants.selected.getBuffUptime(SPELLS.DIRE_FRENZY_TALENT_BUFF_5.id)) / this.owner.fightDuration; } get direFrenzyUptimeThreshold() { return { actual: this.percentUptimePet, isLessThan: { minor: 0.85, average: 0.75, major: 0.7, }, style: 'percentage', }; } get direFrenzy3StackThreshold() { return { actual: this.percentUptimeMaxStacks, isLessThan: { minor: 0.45, average: 0.40, major: 0.35, }, style: 'percentage', }; } suggestions(when) { when(this.direFrenzyUptimeThreshold) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your pet has a general low uptime of the buff from <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} icon />, you should never be sitting on 2 stacks of this spells, if you've chosen this talent, it's your most important spell to continously be casting. </Wrapper>) .icon(SPELLS.DIRE_FRENZY_TALENT.icon) .actual(`Your pet had the buff from Dire Frenzy for ${actual}% of the fight`) .recommended(`${recommended}% is recommended`); }); when(this.direFrenzy3StackThreshold).addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your pet has a general low uptime of the 3 stacked buff from <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} icon />. It's important to try and maintain the buff at 3 stacks for as long as possible, this is done by spacing out your casts, but at the same time never letting them cap on charges. </Wrapper>) .icon(SPELLS.DIRE_FRENZY_TALENT.icon) .actual(`Your pet had 3 stacks of the buff from Dire Frenzy for ${actual}% of the fight`) .recommended(`${recommended}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.DIRE_FRENZY_TALENT.id} />} value={`${formatPercentage(this.percentUptimeMaxStacks)}%`} label={`3 Stack Uptime`} tooltip={`Your pet had an overall uptime of ${formatPercentage(this.percentUptimePet)}% on the increased attack speed buff <br/> You had an uptime of ${formatPercentage(this.percentPlayerUptime)}% on the focus regen buff, this number indicates you had an average of ${(this.percentPlayerUptime).toFixed(2)} stacks of the buff up over the course of the encounter`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(5); subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id}> <SpellIcon id={SPELLS.DIRE_FRENZY_TALENT.id} noLink /> Dire Frenzy </SpellLink> </div> <div className="flex-sub text-right"> <ItemDamageDone amount={this.damage} /> </div> </div> ); } } export default DireFrenzy;
packages/react/components/actions.js
iamxiaoma/Framework7
import React from 'react'; import Mixins from '../utils/mixins'; import Utils from '../utils/utils'; import __reactComponentWatch from '../runtime-helpers/react-component-watch.js'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Actions extends React.Component { constructor(props, context) { super(props, context); this.__reactRefs = {}; (() => { Utils.bindMethods(this, ['onOpen', 'onOpened', 'onClose', 'onClosed']); })(); } onOpen(instance) { this.dispatchEvent('actions:open actionsOpen', instance); } onOpened(instance) { this.dispatchEvent('actions:opened actionsOpened', instance); } onClose(instance) { this.dispatchEvent('actions:close actionsClose', instance); } onClosed(instance) { this.dispatchEvent('actions:closed actionsClosed', instance); } open(animate) { const self = this; if (!self.f7Actions) return undefined; return self.f7Actions.open(animate); } close(animate) { const self = this; if (!self.f7Actions) return undefined; return self.f7Actions.close(animate); } render() { const self = this; const props = self.props; const { className, id, style, grid } = props; const classes = Utils.classNames(className, 'actions-modal', { 'actions-grid': grid }, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, ref: __reactNode => { this.__reactRefs['el'] = __reactNode; }, className: classes }, this.slots['default']); } componentWillUnmount() { const self = this; if (self.f7Actions) self.f7Actions.destroy(); delete self.f7Actions; } componentDidMount() { const self = this; const el = self.refs.el; if (!el) return; const props = self.props; const { grid, target, convertToPopover, forceToPopover, opened, closeByBackdropClick, closeByOutsideClick, closeOnEscape, backdrop, backdropEl } = props; const actionsParams = { el, grid, on: { open: self.onOpen, opened: self.onOpened, close: self.onClose, closed: self.onClosed } }; if (target) actionsParams.targetEl = target; { if ('convertToPopover' in props) actionsParams.convertToPopover = convertToPopover; if ('forceToPopover' in props) actionsParams.forceToPopover = forceToPopover; if ('backdrop' in props) actionsParams.backdrop = backdrop; if ('backdropEl' in props) actionsParams.backdropEl = backdropEl; if ('closeByBackdropClick' in props) actionsParams.closeByBackdropClick = closeByBackdropClick; if ('closeByOutsideClick' in props) actionsParams.closeByOutsideClick = closeByOutsideClick; if ('closeOnEscape' in props) actionsParams.closeOnEscape = closeOnEscape; } self.$f7ready(() => { self.f7Actions = self.$f7.actions.create(actionsParams); if (opened) { self.f7Actions.open(false); } }); } get slots() { return __reactComponentSlots(this.props); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } get refs() { return this.__reactRefs; } set refs(refs) {} componentDidUpdate(prevProps, prevState) { __reactComponentWatch(this, 'props.opened', prevProps, prevState, opened => { const self = this; if (!self.f7Actions) return; if (opened) { self.f7Actions.open(); } else { self.f7Actions.close(); } }); } } __reactComponentSetProps(F7Actions, Object.assign({ id: [String, Number], className: String, style: Object, opened: Boolean, grid: Boolean, convertToPopover: Boolean, forceToPopover: Boolean, target: [String, Object], backdrop: Boolean, backdropEl: [String, Object, window.HTMLElement], closeByBackdropClick: Boolean, closeByOutsideClick: Boolean, closeOnEscape: Boolean }, Mixins.colorProps)); F7Actions.displayName = 'f7-actions'; export default F7Actions;
docs/src/app/components/pages/components/RaisedButton/ExampleIcon.js
pradel/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import {fullWhite} from 'material-ui/styles/colors'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import FontIcon from 'material-ui/FontIcon'; const style = { margin: 12, }; const RaisedButtonExampleIcon = () => ( <div> <RaisedButton icon={<ActionAndroid />} style={style} /> <RaisedButton backgroundColor="#a4c639" icon={<ActionAndroid color={fullWhite} />} style={style} /> <RaisedButton linkButton={true} href="https://github.com/callemall/material-ui" secondary={true} icon={<FontIcon className="muidocs-icon-custom-github" />} style={style} /> </div> ); export default RaisedButtonExampleIcon;
src/mongostick/frontend/src/screens/DatabaseOverview.js
RockingRolli/mongostick
import React from 'react' import { Col, Row, Table } from 'antd' import { connect } from 'react-redux' import { formatBytes } from '../lib/mongodb' import { Link } from 'react-router-dom' class Databases extends React.Component { getColumns = () => { return [ { title: 'Name', dataIndex: 'stats.db', key: 'db', render: text => <Link to={`/databases/overview/${text}`}>{text}</Link> }, { title: 'Collections', dataIndex: 'stats.collections', key: 'collections', sorter: (a, b) => a.stats.collections - b.stats.collections, }, { title: 'Storage Size', dataIndex: 'stats.storageSize', key: 'storageSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.storageSize - b.stats.storageSize, }, { title: 'Data Size', dataIndex: 'stats.dataSize', key: 'dataSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.dataSize - b.stats.dataSize, }, { title: 'AVG Obj Size', dataIndex: 'stats.avgObjSize', key: 'avgObjSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.avgObjSize - b.stats.avgObjSize, }, { title: 'objects', dataIndex: 'stats.objects', key: 'objects', render: text => text.toLocaleString(), sorter: (a, b) => a.stats.objects - b.stats.objects, }, { title: 'Indexes', dataIndex: 'stats.indexes', key: 'indexes', sorter: (a, b) => a.stats.indexes - b.stats.indexes, }, { title: 'Indexes', dataIndex: 'stats.indexSize', key: 'indexSize', render: text => formatBytes(text), sorter: (a, b) => a.stats.indexSize - b.stats.indexSize, }, ] } getDataSource = () => { const { databases } = this.props return Object.keys(databases).map((index) => databases[index]) } render() { return ( <div> <Row style={{ background: '#fff' }}> <Col span={24} style={{ background: '#fff', padding: '10px' }}> <Table dataSource={this.getDataSource()} columns={this.getColumns()} size="small" rowKey={record => record.stats.db} /> </Col> </Row> </div> ) } } const mapStateToProps = store => { return { databases: store.databases, } } export default connect(mapStateToProps)(Databases)
app/addons/documents/routes-mango.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import app from '../../app'; import FauxtonAPI from '../../core/api'; import Databases from '../databases/resources'; import DatabaseActions from '../databases/actions'; import Documents from './shared-resources'; import {MangoLayoutContainer} from './mangolayout'; const MangoIndexEditorAndQueryEditor = FauxtonAPI.RouteObject.extend({ selectedHeader: 'Databases', hideApiBar: true, hideNotificationCenter: true, routes: { 'database/:database/_partition/:partitionkey/_index': { route: 'createIndex', roles: ['fx_loggedIn'] }, 'database/:database/_index': { route: 'createIndexNoPartition', roles: ['fx_loggedIn'] }, 'database/:database/_partition/:partitionkey/_find': { route: 'findUsingIndex', roles: ['fx_loggedIn'] }, 'database/:database/_find': { route: 'findUsingIndexNoPartition', roles: ['fx_loggedIn'] }, }, initialize: function (route, options) { var databaseName = options[0]; this.databaseName = databaseName; this.database = new Databases.Model({id: databaseName}); }, findUsingIndexNoPartition: function (database) { return this.findUsingIndex(database, ''); }, findUsingIndex: function (database, partitionKey) { const encodedPartitionKey = partitionKey ? encodeURIComponent(partitionKey) : ''; const url = FauxtonAPI.urls( 'allDocs', 'app', encodeURIComponent(this.databaseName), encodedPartitionKey ); const partKeyUrlComponent = partitionKey ? `/${encodedPartitionKey}` : ''; const fetchUrl = '/' + encodeURIComponent(this.databaseName) + partKeyUrlComponent + '/_find'; const crumbs = [ {name: database, link: url}, {name: app.i18n.en_US['mango-title-editor']} ]; const endpoint = FauxtonAPI.urls('mango', 'query-apiurl', encodeURIComponent(this.databaseName), encodedPartitionKey); const navigateToPartitionedView = (partKey) => { const baseUrl = FauxtonAPI.urls('mango', 'query-app', encodeURIComponent(database), encodeURIComponent(partKey)); FauxtonAPI.navigate('#/' + baseUrl); }; const navigateToGlobalView = () => { const baseUrl = FauxtonAPI.urls('mango', 'query-app', encodeURIComponent(database)); FauxtonAPI.navigate('#/' + baseUrl); }; return <MangoLayoutContainer database={database} crumbs={crumbs} docURL={FauxtonAPI.constants.DOC_URLS.MANGO_SEARCH} endpoint={endpoint} edit={false} databaseName={this.databaseName} fetchUrl={fetchUrl} partitionKey={partitionKey} onPartitionKeySelected={navigateToPartitionedView} onGlobalModeSelected={navigateToGlobalView} globalMode={partitionKey === ''} />; }, createIndexNoPartition: function (database) { return this.createIndex(database, ''); }, createIndex: function (database, partitionKey) { const designDocs = new Documents.AllDocs(null, { database: this.database, paging: { pageSize: 500 }, params: { startkey: '_design/', endkey: '_design0', include_docs: true, limit: 500 } }); const encodedPartitionKey = partitionKey ? encodeURIComponent(partitionKey) : ''; const url = FauxtonAPI.urls( 'allDocs', 'app', encodeURIComponent(this.databaseName), encodedPartitionKey ); const endpoint = FauxtonAPI.urls('mango', 'index-apiurl', encodeURIComponent(this.databaseName), encodedPartitionKey); const crumbs = [ {name: database, link: url}, {name: app.i18n.en_US['mango-indexeditor-title']} ]; DatabaseActions.fetchSelectedDatabaseInfo(database); return <MangoLayoutContainer showIncludeAllDocs={false} crumbs={crumbs} docURL={FauxtonAPI.constants.DOC_URLS.MANGO_INDEX} endpoint={endpoint} edit={true} designDocs={designDocs} databaseName={this.databaseName} partitionKey={partitionKey} />; } }); export default { MangoIndexEditorAndQueryEditor: MangoIndexEditorAndQueryEditor };
src/Row.js
westonplatter/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
src/components/Layer/Layer.js
nambawan/g-old
// from : https://github.com/grommet/grommet/blob/master/src/js/components/Layer.js import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import withStyles from 'isomorphic-style-loader/withStyles'; import StyleContext from 'isomorphic-style-loader/StyleContext'; import { Provider as ReduxProvider } from 'react-redux'; import { IntlProvider } from 'react-intl'; import cn from 'classnames'; import LayerContents from '../LayerContents'; import s from './Layer.css'; class Layer extends React.Component { static propTypes = { onClose: PropTypes.func.isRequired, id: PropTypes.string, hidden: PropTypes.bool, fill: PropTypes.bool, }; static defaultProps = { id: null, hidden: false, fill: false, }; componentDidMount() { this.originalFocusedElement = document.activeElement; this.originalScrollPosition = { top: window.pageYOffset, left: window.pageXOffset, }; this.addLayer(); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { const { hidden } = this.props; if (this.originalFocusedElement && !hidden) { if (this.originalFocusedElement.focus) { // wait for the fixed positioning to come back to normal // see layer styling for reference setTimeout(() => { this.originalFocusedElement.focus(); window.scrollTo( this.originalScrollPosition.left, this.originalScrollPosition.top, ); }, 0); } else if ( this.originalFocusedElement.parentNode && this.originalFocusedElement.parentNode.focus ) { // required for IE11 and Edge this.originalFocusedElement.parentNode.focus(); window.scrollTo( this.originalScrollPosition.left, this.originalScrollPosition.top, ); } } this.removeLayer(); } addLayer() { const { id } = this.props; const element = document.createElement('div'); if (id) { element.id = id; } element.className = s.layer; const appElements = document.querySelectorAll('#app'); let beforeElement; if (appElements.length > 0) { [beforeElement] = appElements; } else { beforeElement = document.body.firstChild; } if (beforeElement) { this.element = beforeElement.parentNode.insertBefore( element, beforeElement, ); } } removeLayer() { this.element.removeEventListener('animationend', this.onAnimationEnd); ReactDOM.unmountComponentAtNode(this.element); this.element.parentNode.removeChild(this.element); this.element = undefined; this.handleAriaHidden(true); } handleAriaHidden(hideOverlay) { setTimeout(() => { const hidden = hideOverlay || false; const apps = document.querySelectorAll('#app'); const visibleLayers = document.querySelectorAll( `.${s.layer}:not(.${s.hidden})`, ); if (apps) { /* eslint-disable no-param-reassign */ Array.prototype.slice.call(apps).forEach(app => { if (hidden && visibleLayers.length === 0) { // make sure to only show grommet apps if there is no other layer app.setAttribute('aria-hidden', false); app.classList.remove(s.hidden); // scroll body content to the original position app.style.top = `-${this.originalScrollPosition.top}px`; app.style.left = `-${this.originalScrollPosition.left}px`; } else { app.setAttribute('aria-hidden', true); app.classList.add(s.hidden); // this must be null to work app.style.top = null; app.style.left = null; // app.style.top = `-${this.originalScrollPosition.top}px`; // app.style.left = `-${this.originalScrollPosition.left}px`; } }, this); /* eslint-enable no-param-reassign */ } }, 0); } renderLayer() { if (this.element) { this.element.className = s.layer; const { insertCss, store, intl } = this.context; const { onClose, fill } = this.props; const contents = ( <StyleContext.Provider value={{ insertCss }}> <ReduxProvider store={store}> <LayerContents {...this.props} className={cn(s.container, fill && s.fill)} intl={intl} onClose={onClose} /> </ReduxProvider> </StyleContext.Provider> ); ReactDOM.render(contents, this.element, () => { const { hidden } = this.props; if (hidden) { this.handleAriaHidden(true); } else { this.handleAriaHidden(false); } }); } } render() { return null; } } Layer.contextTypes = { insertCss: PropTypes.func.isRequired, intl: IntlProvider.childContextTypes.intl, locale: PropTypes.string, store: PropTypes.shape({ subscribe: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, getState: PropTypes.func.isRequired, }), }; export default withStyles(s)(Layer);
src/components/AppRoutes.js
trda/seslisozluk-simple-ui-project
import React from 'react'; import { Router, browserHistory } from 'react-router'; import routes from '../routes'; export default class AppRoutes extends React.Component { render() { return ( <Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/> ); } }
src/navigators/ReduxNavigation.js
jfilter/frag-den-staat-app
import { BackHandler, Linking, Platform } from 'react-native'; import { NavigationActions } from 'react-navigation'; import { connect } from 'react-redux'; import { createReactNavigationReduxMiddleware, createReduxContainer, } from 'react-navigation-redux-helpers'; import React from 'react'; import BackgroundFetch from 'react-native-background-fetch'; import { GET_REQUEST_ID_HOSTNAME, OAUTH_REDIRECT_URI, ORIGIN, FDROID, } from '../globals'; import I18n from '../i18n'; import { errorAlert, successAlert } from '../utils/dropDownAlert'; import { getUserInformation, receiveOauthRedirectError, oauthUpdateToken, } from '../actions/authentication'; import { loadToken, saveToken } from '../utils/secureStorage'; import AppNavigator from './AppNavigator'; import { fetchInitialToken } from '../utils/oauth'; import { searchUpdateAlertMatchesAction } from '../actions/search'; import { localNotif, setUp } from '../utils/notifications'; // Note: createReactNavigationReduxMiddleware must be run before createReduxBoundAddListener const navMiddleware = createReactNavigationReduxMiddleware( state => state.navigation ); const App = createReduxContainer(AppNavigator, 'root'); class ReduxNavigation extends React.Component { async componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.onBackPress); // universal linking, when app was closed // (and all android calls) Linking.getInitialURL().then(url => { if (url !== null) this.urlRouter(url); }); // deep linking (and all ios) Linking.addEventListener('url', this.handleUrlEvent); const token = await loadToken(); if (token !== null && Object.keys(token).length !== 0) { await this.props.updateToken(token); this.props.getUserInformation(); } const nav = id => { this.props.dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); }; if (!FDROID) setUp(nav); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.onBackPress); Linking.removeEventListener('url', this.handleUrlEvent); } handleUrlEvent = event => this.urlRouter(event.url); onBackPress = () => { const { dispatch, navigation } = this.props; // close the app when pressing back button on initial screen // because everything is wrapped in a Drawer, we need to go over this first // navigator if ( navigation.routes[0].index === 0 && navigation.routes[0].routes[0].index === 0 ) { return false; } dispatch(NavigationActions.back()); return true; }; urlRouter = url => { if (url.startsWith(OAUTH_REDIRECT_URI)) { this.handleLoginRedirect(url); } else { this.navigate(url); } }; handleLoginRedirect = url => { // 1. go back to page where clicked login (on iOS) if (Platform.OS === 'ios') this.props.dispatch(NavigationActions.back()); fetchInitialToken(url) .then(token => { // 2. show message on top successAlert .getDropDown() .alertWithType( 'success', I18n.t('loginSuccess'), I18n.t('loginSuccessMessage') ); // 3. update token in redux store this.props.updateToken(token); // 4. fetch information about user from server this.props.getUserInformation(); // 5. persists token saveToken(token); }) .catch(error => errorAlert.getDropDown().alertWithType('error', 'Error', error.message) ); }; navigate = async url => { const { dispatch } = this.props; // difference for deep linking and unviversal linking let route; if (url.startsWith(ORIGIN)) { route = url.replace(`${ORIGIN}/`, ''); } else { route = url.replace(/.*?:\/\//g, ''); } const routeParts = route .split('#')[0] .split('/') .filter(x => x.length > 0); const routeName = routeParts[0]; // a for anfrage if (routeName === 'a') { // short url with the request id const id = route.match(/\/([^\/]+)\/?$/)[1]; dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); } if (routeName === 'anfrage' && routeParts.length !== 5) { // open request (defined by slug) in app // TODO: currently the same request is fetched twice const slug = routeParts.reverse()[0]; const res = await fetch(`${ORIGIN}/api/v1/request/?slug=${slug}`); const id = (await res.json()).objects[0].id; dispatch( NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }) ); } if (routeName === 'anfrage' && routeParts.length === 5) { // open an attachment in app const messageId = routeParts[2]; const res = await fetch( `https://fragdenstaat.de/api/v1/message/${messageId}` ); const message = await res.json(); const id = message.request.split('/').reverse()[1]; message.attachments.forEach(x => { if (x.name.toLowerCase() === routeParts[4].toLowerCase()) { const action1 = NavigationActions.navigate({ routeName: 'FoiRequestsSingle', params: { foiRequestId: id }, }); // first to request, then to attachment dispatch(action1); const action2 = NavigationActions.navigate({ routeName: 'FoiRequestsPdfViewer', params: { url: x.site_url, fileUrl: x.file_url }, }); dispatch(action2); } }); } }; render() { const { pastAlertMatches, alerts, hasNotificationPermission, searchUpdateAlertMatches, } = this.props; // background stuff if (hasNotificationPermission && alerts.length) { BackgroundFetch.configure( { minimumFetchInterval: 60, // <-- minutes (15 is minimum allowed) stopOnTerminate: false, // <-- Android-only, startOnBoot: true, // <-- Android-only, enableHeadless: true, }, async () => { console.log('[js] Received background-fetch event'); const data = await Promise.all( alerts.map(async x => { const response = await fetch( `https://fragdenstaat-alerts.app.vis.one/min/${x}` ); console.log(response); const responseJson = await response.json(); return { terms: x, res: responseJson }; }) ); console.log(pastAlertMatches); data.forEach(x => { x.res.forEach(({ id }) => { // only works on request ids and not message ids. if ( pastAlertMatches[x.terms] === undefined || pastAlertMatches[x.terms].indexOf(id) < 0 ) { localNotif(`Neuer Treffer für "${x.terms}"`, id); } searchUpdateAlertMatches(x.terms, id); }); }); console.log(data); BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA); }, error => { console.log('[js] RNBackgroundFetch failed to start', error); } ); // Optional: Query the authorization status. BackgroundFetch.status(status => { switch (status) { case BackgroundFetch.STATUS_RESTRICTED: console.log('BackgroundFetch restricted'); break; case BackgroundFetch.STATUS_DENIED: console.log('BackgroundFetch denied'); break; case BackgroundFetch.STATUS_AVAILABLE: console.log('BackgroundFetch is enabled'); break; default: console.log('default'); } }); } const { navigation, dispatch } = this.props; return <App state={navigation} dispatch={dispatch} />; } } const mapStateToProps = state => ({ navigation: state.navigation, alerts: state.search.alerts, pastAlertMatches: state.search.pastAlertMatches, hasNotificationPermission: state.settings.hasNotificationPermission, }); const mapDispatchToProps = dispatch => ({ updateToken: token => dispatch(oauthUpdateToken(token)), redirectError: errorMessage => dispatch(receiveOauthRedirectError(errorMessage)), getUserInformation: () => dispatch(getUserInformation()), searchUpdateAlertMatches: (term, id) => dispatch(searchUpdateAlertMatchesAction(term, id)), dispatch, }); const AppWithNavigationState = connect( mapStateToProps, mapDispatchToProps )(ReduxNavigation); export { AppWithNavigationState, navMiddleware };
node_modules/react-bootstrap/es/Popover.js
darklilium/Factigis_2
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * Title content */ title: React.PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: 'arrow', style: arrowStyle }), title && React.createElement( 'h3', { className: prefix(bsProps, 'title') }, title ), React.createElement( 'div', { className: prefix(bsProps, 'content') }, children ) ); }; return Popover; }(React.Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);
admin/client/App/components/Navigation/Mobile/SectionItem.js
benkroeger/keystone
/** * A mobile section */ import React from 'react'; import MobileListItem from './ListItem'; import { Link } from 'react-router'; const MobileSectionItem = React.createClass({ displayName: 'MobileSectionItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, currentListKey: React.PropTypes.string, href: React.PropTypes.string.isRequired, lists: React.PropTypes.array, }, // Render the lists renderLists () { if (!this.props.lists || this.props.lists.length <= 1) return null; const navLists = this.props.lists.map((item) => { // Get the link and the classname const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`; const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item'; return ( <MobileListItem key={item.path} href={href} className={className} onClick={this.props.onClick}> {item.label} </MobileListItem> ); }); return ( <div className="MobileNavigation__lists"> {navLists} </div> ); }, render () { return ( <div className={this.props.className}> <Link className="MobileNavigation__section-item" to={this.props.href} tabIndex="-1" onClick={this.props.onClick} > {this.props.children} </Link> {this.renderLists()} </div> ); }, }); module.exports = MobileSectionItem;
client/components/ui/label.js
bnjbvr/kresus
import React from 'react'; import PropTypes from 'prop-types'; import { translate as $t } from '../../helpers'; class LabelComponent extends React.Component { state = { value: null }; handleChange = e => { this.setState({ value: e.target.value }); }; handleFocus = event => { // Set the caret at the end of the text. let end = (event.target.value || '').length; event.target.selectionStart = end; event.target.selectionEnd = end; }; handleKeyUp = event => { if (event.key === 'Enter') { event.target.blur(); } else if (event.key === 'Escape') { let { target } = event; this.setState( { value: null }, () => target.blur() ); } }; handleBlur = () => { if (this.state.value === null) { return; } let label = this.state.value.trim(); // If the custom label is equal to the label, remove the custom label. if (label === this.props.getLabel()) { label = ''; } let { customLabel } = this.props.item; if (label !== customLabel && (label || customLabel)) { this.props.setCustomLabel(label); } this.setState({ value: null }); }; getCustomLabel() { let { customLabel } = this.props.item; if (customLabel === null || !customLabel.trim().length) { return ''; } return customLabel; } getDefaultValue() { let label = this.getCustomLabel(); if (!label && this.props.displayLabelIfNoCustom) { label = this.props.getLabel(); } return label; } render() { let label = this.state.value !== null ? this.state.value : this.getDefaultValue(); let forceEditMode = this.props.forceEditMode ? 'force-edit-mode' : ''; return ( <div className={`label-component-container ${forceEditMode}`}> <span>{label}</span> <input className="form-element-block" type="text" value={label} onChange={this.handleChange} onFocus={this.handleFocus} onKeyUp={this.handleKeyUp} onBlur={this.handleBlur} placeholder={$t('client.general.add_custom_label')} /> </div> ); } } LabelComponent.propTypes /* remove-proptypes */ = { // The item from which to get the label. item: PropTypes.object.isRequired, // Whether to display the label if there is no custom label. displayLabelIfNoCustom: PropTypes.bool, // A function to set the custom label when modified. setCustomLabel: PropTypes.func.isRequired, // Force the display of the input even on small screens forceEditMode: PropTypes.bool, // A function that returns the displayed label. getLabel: PropTypes.func.isRequired }; LabelComponent.defaultProps = { displayLabelIfNoCustom: true, forceEditMode: false }; export default LabelComponent;
src/svg-icons/av/explicit.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvExplicit = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"/> </SvgIcon> ); AvExplicit = pure(AvExplicit); AvExplicit.displayName = 'AvExplicit'; AvExplicit.muiName = 'SvgIcon'; export default AvExplicit;
src/components/ExplanationSelection.js
quintel/etmobile
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import offSvg from '../images/explanations/off.svg'; import onSvg from '../images/explanations/on.svg'; import offSelectedSvg from '../images/explanations/off-selected.svg'; import onSelectedSvg from '../images/explanations/on-selected.svg'; class ExplanationSelection extends React.Component { constructor() { super(); this.state = { selected: null }; this.choose = this.choose.bind(this); } selectedValue() { if (this.state.selected !== null) { return this.state.selected; } return this.props.selected; } choose(event) { const showExplanations = event.target.value === 'yes'; this.props.onChange(showExplanations); this.setState({ selected: showExplanations }); } render() { const selected = this.selectedValue(); const yesClasses = classNames({ selected: selected === true }); const noClasses = classNames({ selected: selected !== true }); let yesImg = onSvg; let noImg = offSelectedSvg; if (selected) { yesImg = onSelectedSvg; noImg = offSvg; } return ( <div className="app-option explanation-selection"> <span className="prompt"> <FormattedMessage id="app.showExplanations" /> </span> <ul> <li className={yesClasses}> <button onClick={this.choose} value="yes" className="yes" style={{ backgroundImage: `url(${yesImg})` }} > <FormattedMessage id="app.yes" /> </button> </li> <li className={noClasses}> <button onClick={this.choose} value="no" className="no" style={{ backgroundImage: `url(${noImg})` }} > <FormattedMessage id="app.no" /> </button> </li> </ul> </div> ); } } ExplanationSelection.propTypes = { selected: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired }; export default ExplanationSelection;
src/views/Components/NavigationTree.js
pranked/cs2-web
/** * Created by dom on 9/15/16. */ import React from 'react'; import { Link } from 'react-router'; const NavigationTree = React.createClass({ propTypes: { items: React.PropTypes.array.isRequired }, render() { const flatten = (item) => { return ( <li key={item.name}> <Link to={item.url} activeClassName="selected">{item.name}</Link> </li> ); }; return ( <ul className="nav nav-pills"> {this.props.items.map(flatten)} </ul> ); } }); export default NavigationTree;
app/javascript/mastodon/features/compose/components/warning.js
SerCom-KC/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; export default class Warning extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, }; render () { const { message } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='compose-form__warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> {message} </div> )} </Motion> ); } }
stalk-messenger/app/components/tabs/chats/index.js
JohnKim/stalk.messenger
/** * * @flow */ 'use strict'; import React, { Component } from 'react'; import { View, StyleSheet, Text, TouchableOpacity, } from 'react-native'; import ChatCell from './ChatCell'; import { loadChats, leaveChat } from 's5-action'; import { S5Header, S5SwipeListView } from 's5-components'; import { connect } from 'react-redux'; import ActionButton from 'react-native-action-button'; class ChatsScreen extends Component { static propTypes = { chats: React.PropTypes.object.isRequired, messages: React.PropTypes.object.isRequired, user: React.PropTypes.object, navigator: React.PropTypes.object.isRequired, leaveChat: React.PropTypes.func.isRequired, }; state = { listViewData: [] }; constructor(props) { super(props); this._openAddUserView = this._openAddUserView.bind(this); } componentDidMount(){ this.setState({ listViewData: this.props.chats.list }); } componentWillReceiveProps (nextProps) { if (nextProps.chats.list !== this.props.chats.list) { this.setState({ listViewData: nextProps.chats.list }); } } _onRowPress(chat) { this.props.navigator.push({ chatView: true, chat, }); } _deleteRow(secId, rowId, rowMap, chatId) { rowMap[`${secId}${rowId}`].closeRow(); this.props.leaveChat(chatId).then(() => { // TODO do something after deleting. }); } _openAddUserView() { this.props.navigator.push({selectUserView: 1}); } _renderRow(chat) { return ( <ChatCell key={chat.id} chat={chat} message={this.props.messages.latest[chat.channelId]} onPress={() => this._onRowPress(chat)} /> ) } render() { return ( <View style={styles.container}> <S5Header title="Chats" style={{backgroundColor: '#224488'}} /> <S5SwipeListView ref="listView" data={this.state.listViewData} renderRow={ (data) => this._renderRow(data) } renderHiddenRow={ (data, secId, rowId, rowMap) => ( <View style={styles.rowBack}> <View style={[styles.backRightBtn, styles.backRightBtnLeft]}> <Text style={styles.backTextWhite}>Mark as Read</Text> </View> <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={ () => this._deleteRow(secId, rowId, rowMap, data.id) }> <Text style={styles.backTextWhite}>Leave</Text> </TouchableOpacity> </View> ) } enableEmptySections={true} rightOpenValue={-150} removeClippedSubviews={false} /> <ActionButton buttonColor="rgba(231,76,60,1)" onPress={this._openAddUserView} /> </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'white', flex: 1 }, standalone: { marginTop: 30, marginBottom: 30, }, standaloneRowFront: { alignItems: 'center', backgroundColor: '#CCC', justifyContent: 'center', height: 50, }, standaloneRowBack: { alignItems: 'center', backgroundColor: '#8BC645', flex: 1, flexDirection: 'row', justifyContent: 'space-between', padding: 15 }, backTextWhite: { color: '#FFF' }, rowFront: { alignItems: 'center', backgroundColor: '#CCC', borderBottomColor: 'black', borderBottomWidth: 1, justifyContent: 'center', height: 50, }, rowBack: { alignItems: 'center', backgroundColor: '#DDD', flex: 1, flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 15, }, backRightBtn: { alignItems: 'center', bottom: 0, justifyContent: 'center', position: 'absolute', top: 0, width: 75 }, backRightBtnLeft: { backgroundColor: 'blue', right: 75 }, backRightBtnRight: { backgroundColor: 'red', right: 0 }, controls: { alignItems: 'center', marginBottom: 30 }, switchContainer: { flexDirection: 'row', justifyContent: 'center', marginBottom: 5 }, switch: { alignItems: 'center', borderWidth: 1, borderColor: 'black', paddingVertical: 10, width: 100, } }); function select(store) { return { user: store.user, chats: store.chats, messages: store.messages, }; } function actions(dispatch) { return { loadChats: () => dispatch(loadChats()), // @ TODO not used !! leaveChat: (chatId) => dispatch(leaveChat(chatId)), }; } module.exports = connect(select, actions)(ChatsScreen);
lib/editor/components/question_editors/parts/BulkAddItemsEditorPart.js
jirokun/survey-designer-js
/* eslint-env browser */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import S from 'string'; import * as EditorActions from '../../../actions'; class BulkAddItemsEditorPart extends Component { constructor(props) { super(props); this.state = { inputText: '' }; } /** 一括追加を実行する */ handleBulkAddItems() { const { bulkAddItems, bulkAddSubItems, handleExecute, page, question, isTargetSubItems } = this.props; if (isTargetSubItems) { bulkAddSubItems(page.getId(), question.getId(), this.state.inputText); } else { bulkAddItems(page.getId(), question.getId(), this.state.inputText); } handleExecute(); } /** タブを改行に置換する */ handleClickConvertTabToLineBreak() { const replacedStr = this.state.inputText.replace(/\t/g, '\n'); this.setState({ inputText: replacedStr }); } /** 空行を削除する */ handleClickDeleteEmptyLines() { const lines = this.state.inputText.split(/\n/); const replacedStr = lines.filter(line => !S(line).isEmpty()).join('\n'); this.setState({ inputText: replacedStr }); } render() { return ( <div> <div>1行に1項目を指定してください。HTMLも指定可能です。</div> <div><textarea className="item-bulk-add-editor" value={this.state.inputText} onChange={e => this.setState({ inputText: e.target.value })} /></div> <div className="clearfix"> <div className="btn-group pull-right"> <button type="button" className="btn btn-info" onClick={() => this.handleClickConvertTabToLineBreak()}>タブを改行に変換</button> <button type="button" className="btn btn-info" onClick={() => this.handleClickDeleteEmptyLines()}>空行の削除</button> <button type="button" className="btn btn-primary" onClick={() => this.handleBulkAddItems()}>一括追加</button> </div> </div> </div> ); } } const stateToProps = state => ({ survey: state.getSurvey(), runtime: state.getRuntime(), view: state.getViewSetting(), options: state.getOptions(), }); const actionsToProps = dispatch => ({ bulkAddItems: (pageId, questionId, text) => dispatch(EditorActions.bulkAddItems(pageId, questionId, text)), bulkAddSubItems: (pageId, questionId, text) => dispatch(EditorActions.bulkAddSubItems(pageId, questionId, text)), }); export default connect( stateToProps, actionsToProps, )(BulkAddItemsEditorPart);
test/integration/image-component/default/pages/missing-src.js
zeit/next.js
import React from 'react' import Image from 'next/image' const Page = () => { return ( <div> <Image width={200}></Image> </div> ) } export default Page
src/js/components/icons/base/ShieldSecurity.js
odedre/grommet-final
/** * @description ShieldSecurity SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M12,22 C12,22 2.99999999,18 3,11 L3,5 L12,2 L21,5 C21,5 21,11 21,11 C21,18 12,22 12,22 Z M12,14 C13.6568542,14 15,12.6568542 15,11 C15,9.34314575 13.6568542,8 12,8 C10.3431458,8 9,9.34314575 9,11 C9,12.6568542 10.3431458,14 12,14 Z M12,8 L12,5 M12,17 L12,14 M6,11 L9,11 M15,11 L18,11 M8,7 L10,9 M14,13 L16,15 M16,7 L14,9 M10,13 L8,15"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-shield-security`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'shield-security'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,22 C12,22 2.99999999,18 3,11 L3,5 L12,2 L21,5 C21,5 21,11 21,11 C21,18 12,22 12,22 Z M12,14 C13.6568542,14 15,12.6568542 15,11 C15,9.34314575 13.6568542,8 12,8 C10.3431458,8 9,9.34314575 9,11 C9,12.6568542 10.3431458,14 12,14 Z M12,8 L12,5 M12,17 L12,14 M6,11 L9,11 M15,11 L18,11 M8,7 L10,9 M14,13 L16,15 M16,7 L14,9 M10,13 L8,15"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'ShieldSecurity'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
actor-apps/app-web/src/app/components/common/Fold.React.js
luwei2012/actor-platform
/* eslint-disable */ import React from 'react'; import classnames from 'classnames'; class Fold extends React.Component { static PropTypes = { icon: React.PropTypes.string, iconClassName: React.PropTypes.string, title: React.PropTypes.string.isRequired }; state = { isOpen: false }; constructor(props) { super(props); } render() { const { icon, iconClassName, title, iconElement } = this.props; const titleIconClassName = classnames('material-icons icon', iconClassName); const className = classnames({ 'fold': true, 'fold--open': this.state.isOpen }); let foldIcon; if (icon) { foldIcon = <i className={titleIconClassName}>{icon}</i>; } if (iconElement) { foldIcon = iconElement; } return ( <div className={className}> <div className="fold__title" onClick={this.onClick}> {foldIcon} {title} <i className="fold__indicator material-icons pull-right">arrow_drop_down</i> </div> <div className="fold__content"> {this.props.children} </div> </div> ); } onClick = () => { this.setState({isOpen: !this.state.isOpen}); }; } export default Fold;
src/propTypes/TextStylePropTypes.js
lelandrichardson/react-native-mock
/** * https://github.com/facebook/react-native/blob/master/Libraries/Text/TextStylePropTypes.js */ import React from 'react'; import ColorPropType from './ColorPropType'; import ViewStylePropTypes from './ViewStylePropTypes'; const { PropTypes } = React; // TODO: use spread instead of Object.assign/create after #6560135 is fixed const TextStylePropTypes = Object.assign(Object.create(ViewStylePropTypes), { color: ColorPropType, fontFamily: PropTypes.string, fontSize: PropTypes.number, fontStyle: PropTypes.oneOf(['normal', 'italic']), /** * Specifies font weight. The values 'normal' and 'bold' are supported for * most fonts. Not all fonts have a variant for each of the numeric values, * in that case the closest one is chosen. */ fontWeight: PropTypes.oneOf( ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'] ), textShadowOffset: PropTypes.shape( { width: PropTypes.number, height: PropTypes.number } ), textShadowRadius: PropTypes.number, textShadowColor: ColorPropType, /** * @platform ios */ letterSpacing: PropTypes.number, lineHeight: PropTypes.number, /** * Specifies text alignment. The value 'justify' is only supported on iOS. */ textAlign: PropTypes.oneOf( ['auto', 'left', 'right', 'center', 'justify'] ), /** * @platform android */ textAlignVertical: PropTypes.oneOf( ['auto', 'top', 'bottom', 'center'] ), /** * @platform ios */ textDecorationLine: PropTypes.oneOf( ['none', 'underline', 'line-through', 'underline line-through'] ), /** * @platform ios */ textDecorationStyle: PropTypes.oneOf( ['solid', 'double', 'dotted', 'dashed'] ), /** * @platform ios */ textDecorationColor: ColorPropType, /** * @platform ios */ writingDirection: PropTypes.oneOf( ['auto', 'ltr', 'rtl'] ), }); module.exports = TextStylePropTypes;
components/DefaultHTMLLayout.js
slidewiki/slidewiki-platform
import React from 'react'; import ApplicationStore from '../stores/ApplicationStore'; //import ga from '../plugins/googleAnalytics/ga'; import { Microservices } from '../configs/microservices'; let hook = require('css-modules-require-hook'); hook({ generateScopedName: '[hash:base64:5]', }); class DefaultHTMLLayout extends React.Component { render() { let user = this.props.context.getUser(); let pageDescription = this.props.context.getStore(ApplicationStore).getPageDescription(); return ( <html lang={ this.props.lang }> <head> <meta charSet="utf-8" /> <title>{this.props.context.getStore(ApplicationStore).getPageTitle()}</title> <meta name="thumbnail" content={this.props.context.getStore(ApplicationStore).getPageThumbnail()} /> <meta property="og:title" content={this.props.context.getStore(ApplicationStore).getPageTitle()} /> <meta property="og:type" content="website" /> <meta property="og:image" content={this.props.context.getStore(ApplicationStore).getPageThumbnail()} /> {pageDescription ? <meta property="og:description" content={pageDescription} /> : ''} <meta name="viewport" content="width=device-width" /> <link href="/assets/custom-semantic-ui/dist/semantic.min.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/custom.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/home-custom.css" rel="stylesheet" type="text/css" /> <link href="/assets/css/home-layout.css" rel="stylesheet" type="text/css" /> <link href="/sweetalert2/dist/sweetalert2.min.css" rel="stylesheet" type="text/css" /> <link href="/custom_modules/reveal.js/css/reveal.css" rel="stylesheet" type="text/css" /> <link href="/custom_modules/reveal.js/lib/css/zenburn.css" rel="stylesheet" type="text/css" /> <link href="/glidejs/dist/css/glide.core.min.css" rel="stylesheet" type="text/css" /> <link href="/glidejs/dist/css/glide.theme.min.css" rel="stylesheet" type="text/css" /> { user ? <link href="/jquery-ui-dist/jquery-ui.min.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="jquery-ui" /> } { user ? <link href="/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="font-awesome" /> } { user ? <link href="/jquery-contextmenu/dist/jquery.contextMenu.min.css" rel="stylesheet" type="text/css" /> : <meta name="placeholder" content="jquery.contextMenu" /> } {/* Vendors css bundle */ this.props.addAssets ? <link href="/public/css/vendor.bundle.css" rel="stylesheet" type="text/css" />: <style></style> } {/*<link href="/custom_modules/reveal.js/css/print/pdf.css" rel="stylesheet" type="text/css" />*/} {/* we add this config option for mathjax so we can better control when the typesetting will occur */} <script type="text/x-mathjax-config" dangerouslySetInnerHTML={{__html:'MathJax.Hub.Config({skipStartupTypeset: true});'}}></script> <script src="/mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML" defer></script> </head> <body> <div id="app" aria-hidden="false" dangerouslySetInnerHTML={{__html: this.props.markup}}></div> {/* Following are added only to support IE browser */} <script src="/es5-shim/es5-shim.min.js"></script> <script src="/es5-shim/es5-sham.min.js"></script> <script src="/json3/lib/json3.min.js"></script> <script src="/es6-shim/es6-shim.min.js"></script> <script src="/es6-shim/es6-sham.min.js"></script> {/* Above are added only to support IE browser */} <script dangerouslySetInnerHTML={{__html: this.props.state}}></script> <script src="/jquery/dist/jquery.min.js"></script> {/* TODO: load specific parts of jquery UI for performance */} { user ? <script src="/jquery-ui-dist/jquery-ui.min.js" defer></script> : '' } <script src="/glidejs/dist/glide.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/progress.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/accordion.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/transition.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/popup.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/dropdown.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/checkbox.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/dimmer.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/modal.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/form.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/tab.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/search.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/api.min.js" defer></script> <script src="/assets/custom-semantic-ui/dist/components/sidebar.min.js" defer></script> {/* All external vendors bundle*/ this.props.addAssets ? <script src={'/public/js/vendor.bundle.js'} defer></script> : '' } { user ? <script src="/ckeditor/ckeditor.js" defer></script> : '' } <script src={ Microservices.webrtc.uri + '/socket.io/socket.io.js' }></script> <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> <script src="/headjs/dist/1.0.0/head.min.js"></script> {/* Adding for dependency loading with reveal.js*/} <script src="/custom_modules/reveal.js/js/reveal.js" defer></script> {/* Main app settings */} <script src="/public/js/settings.js" defer></script> {/* Main app bundle */} <script src={'/public/js/' + this.props.clientFile} defer></script> {/*<script type="text/javascript" src="https://slidewiki.atlassian.net/s/5e2fc7b2a8ba40bc00a09a4f81a301c8-T/rfg5q6/100012/c/1000.0.9/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?locale=en-UK&collectorId=241c9e18" defer></script>*/} <script src="/sweetalert2/dist/sweetalert2.min.js" defer></script> { user ? <script src="/jquery-contextmenu/dist/jquery.contextMenu.min.js" defer></script> : '' } {/*<script src="/custom_modules/simple-draggable/lib/index.js"></script> <script src="/custom_modules/slide-edit-input-controls/lib/index.js"></script>*/} {/*<script>hljs.initHighlightingOnLoad();</script>*/} {/*<script dangerouslySetInnerHTML={ {__html: ga} } />*/} </body> </html> ); } } export default DefaultHTMLLayout;
dashboard-ui/app/components/usageAnalytics/usageAnalytics.js
CloudBoost/cloudboost
/** * Created by Jignesh on 28-06-2017. */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { resetAnalytics } from '../../actions'; export class AppAnalytics extends React.Component { static propTypes = { appData: PropTypes.any, resetAnalytics: PropTypes.any } constructor (props) { super(props); this.state = { noData: false }; } static get contextTypes () { return { router: React.PropTypes.object.isRequired }; } componentWillMount () { // redirect if active app not found if (!this.props.appData.viewActive) { this.context.router.push(window.DASHBOARD_BASE_URL); }// else { // this.props.fetchAppAnalytics(this.props.appData.appId); // } } componentDidMount () { this.buildMonthyGraph(); this.buildDailyGraph(); } componentWillUnmount () { this.props.resetAnalytics(); } buildMonthyGraph () { // eslint-disable-next-line let MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; // eslint-disable-next-line let config = { type: 'line', data: { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'Unique Active registered users', fill: false, backgroundColor: 'rgb(54, 162, 235)', borderColor: 'rgb(54, 162, 235)', data: [ (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 1000) ] }] }, options: { responsive: true, title: { display: true, text: 'Monthly Active Users' }, tooltips: { mode: 'index', intersect: false }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Month' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Active Users' } }] } } }; return document.getElementById('graph').getContext('2d'); } buildDailyGraph () { // eslint-disable-next-line let config = { type: 'line', data: { labels: ['29th May', '30', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '28th July'], datasets: [{ label: 'Unique Active registered users', fill: false, backgroundColor: 'rgb(54, 162, 235)', borderColor: 'rgb(54, 162, 235)', data: [ (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100), (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100) ] }] }, options: { responsive: true, title: { display: true, text: 'Daily Active Users' }, tooltips: { mode: 'index', intersect: false }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Day' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Active Users' } }] } } }; return document.getElementById('graph2').getContext('2d'); } render () { return ( <div className='panel-body' style={{ backgroundColor: '#FFF' }}> <div className='app-analytics' style={{ textAlign: 'center' }}> <h5>45 Active Users at { new Date().toLocaleTimeString() }</h5> </div> <br /> <div className='app-analytics' style={{ width: '75%' }}> { (this.state.noData === false) && <canvas id='graph' /> } { (this.state.noData === true) && <div style={{ width: '100%', height: '100%' }} className='flex-general-column-wrapper-center'> <div> <span style={{ fontSize: 20, color: '#D1D1D1' }}>Monthly Data not available</span> </div> </div> } </div> <div className='app-analytics' style={{ width: '75%' }}> { (this.state.noData === false) && <canvas id='graph2' /> } { (this.state.noData === true) && <div style={{ width: '100%', height: '100%' }} className='flex-general-column-wrapper-center'> <div> <span style={{ fontSize: 20, color: '#D1D1D1' }}>Daily Data not available</span> </div> </div> } </div> </div> ); } } const mapStateToProps = (state) => { return { appData: state.manageApp // analyticsApi: state.analytics.appAnalytics }; }; const mapDispatchToProps = (dispatch) => { return { // fetchAppAnayltics: (appId) => dispatch(fetchAppAnayltics(appId)), resetAnalytics: () => dispatch(resetAnalytics()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(AppAnalytics);
examples/parcel/src/withRoot.js
cherniavskii/material-ui
import React from 'react'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'; import purple from 'material-ui/colors/purple'; import green from 'material-ui/colors/green'; import CssBaseline from 'material-ui/CssBaseline'; // A theme with custom primary and secondary color. // It's optional. const theme = createMuiTheme({ palette: { primary: { light: purple[300], main: purple[500], dark: purple[700], }, secondary: { light: green[300], main: green[500], dark: green[700], }, }, }); function withRoot(Component) { function WithRoot(props) { // MuiThemeProvider makes the theme available down the React tree // thanks to React context. return ( <MuiThemeProvider theme={theme}> {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */} <CssBaseline /> <Component {...props} /> </MuiThemeProvider> ); } return WithRoot; } export default withRoot;
docs/app/Examples/elements/Image/Types/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const ImageTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Image' description='An image.' examplePath='elements/Image/Types/ImageExampleImage' > <Message> Unless a size is specified, images will use the original dimensions of the image up to the size of its container. </Message> </ComponentExample> <ComponentExample description='An image can render wrapped in a div.ui.image as alternative HTML markup.' examplePath='elements/Image/Types/ImageExampleWrapped' /> <ComponentExample title='Image Link' description='An image can be formatted to link to other content.' examplePath='elements/Image/Types/ImageExampleLink' /> </ExampleSection> ) export default ImageTypesExamples
router_tutorial/06-params/modules/About.js
Muzietto/react-playground
import React from 'react' export default React.createClass({ render() { return <div>About</div> } })
code/workspaces/web-app/src/pages/Page.js
NERC-CEH/datalab
import React from 'react'; import PropTypes from 'prop-types'; import { Typography, withStyles } from '@material-ui/core'; import Footer from '../components/app/Footer'; const style = theme => ({ pageTemplate: { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: `0 ${theme.spacing(4)}px`, margin: '0 auto', width: '100%', minWidth: '400px', maxWidth: '1000px', }, contentArea: { flexGrow: 1, }, title: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), }, }); function Page({ title, children, className, classes }) { return ( <div className={getClassname(classes.pageTemplate, className)}> {title ? <Typography variant="h4" className={classes.title}>{title}</Typography> : null} <div className={classes.contentArea}> {children} </div> <Footer/> </div> ); } const getClassname = (...classNames) => (classNames.filter(item => item).join(' ')); Page.propTypes = { title: PropTypes.string, classes: PropTypes.object.isRequired, }; export default withStyles(style)(Page);
src/components/routes/animal/AnimalForm.js
fredmarques/petshop
import './Animal.css'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import { registerAnimal } from '../../../actions/animals'; class AnimalForm extends Component { renderField(field) { const { meta: { touched, error } } = field; const className = ''; return ( <div className={className}> <input className="form-control" type={field.type} placeholder={field.placeholder} {...field.input} /> <div className="text-help"> {touched ? error : ''} </div> </div> ); } onSubmit(values) { this.props.registerAnimal(values) } render() { const { handleSubmit } = this.props; return ( <div className={'animalForm'}> <h3>Cadastre seu pet</h3> <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className={'form-inline'}> <Field name="name" label="Nome" placeholder="Nome" type="text" component={this.renderField} /> <Field name="id" label="ID" placeholder="ID" type="text" component={this.renderField} /> <Field name="age" label="Idade" placeholder="Idade" type="text" component={this.renderField} /> <Field name="breed" label="Raça" placeholder="Raça" component={this.renderField} /> <button type="submit" className="btn btn-primary">Entrar</button> <Link to="/" className="btn btn-danger">Cancelar</Link> </form> </div> ); } } export default reduxForm({ form: 'Animal' })( connect(null, {registerAnimal})(AnimalForm) );
src/icons/BorderClearIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class BorderClearIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M14 10h4V6h-4v4zm0 16h4v-4h-4v4zm0 16h4v-4h-4v4zm8-8h4v-4h-4v4zm0 8h4v-4h-4v4zM6 42h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4v-4H6v4zm0-8h4V6H6v4zm16 16h4v-4h-4v4zm16 8h4v-4h-4v4zm0-8h4v-4h-4v4zm0 16h4v-4h-4v4zm0-24h4v-4h-4v4zm-16 0h4v-4h-4v4zM38 6v4h4V6h-4zm-16 4h4V6h-4v4zm8 32h4v-4h-4v4zm0-16h4v-4h-4v4zm0-16h4V6h-4v4z"/></svg>;} };